When the state value is delivered to the sub-component, ts2322 era comes out. How do I fix it?
It's not a problem when transferring a function, but it's a problem when transferring a state.
import React, { useEffect, useState } from "react";
import DashboardUI from "./DashboardMain.presenter";
import axios from "axios";
const DashboardContainer = () => {
const request = "http://localhost:4000/requests";
// interface Iprops {
// id: number;
// title: string;
// client: string;
// due: string;
// count: number;
// amount: number;
// method: string[];
// material: string[];
// status: string;
// }
const [renderData, setRenderData] = useState();
useEffect(() => {
async function getData() {
const response: any = await axios.get(request);
console.log(response);
setRenderData(response.data);
console.log(renderData);
}
getData();
}, []);
return <DashboardUI renderData={renderData} />;
};
There is a problem in this area.
CodePudding user response:
This is a problem because the state is initially initialized to undefined
It seems that TypeScript checks for errors because the state has a undefined value before data fetching is finished.
- Check renderData to render
import React, { useEffect, useState } from "react";
import DashboardUI from "./DashboardMain.presenter";
import axios from "axios";
const DashboardContainer = () => {
const request = "http://localhost:4000/requests";
// interface Iprops {
// id: number;
// title: string;
// client: string;
// due: string;
// count: number;
// amount: number;
// method: string[];
// material: string[];
// status: string;
// }
const [renderData, setRenderData] = useState(null);
useEffect(() => {
async function getData() {
const response: any = await axios.get(request);
console.log(response);
setRenderData(response.data);
console.log(renderData);
}
getData();
}, []);
if(!renderData) return null
return <DashboardUI renderData={renderData} />;
};
- use down casting
import React, { useEffect, useState } from "react";
import DashboardUI from "./DashboardMain.presenter";
import axios from "axios";
const DashboardContainer = () => {
const request = "http://localhost:4000/requests";
// interface Iprops {
// id: number;
// title: string;
// client: string;
// due: string;
// count: number;
// amount: number;
// method: string[];
// material: string[];
// status: string;
// }
const [renderData, setRenderData] = useState(null);
useEffect(() => {
async function getData() {
const response: any = await axios.get(request);
console.log(response);
setRenderData(response.data);
console.log(renderData);
}
getData();
}, []);
return <DashboardUI renderData={renderData as Iprops} />;
};
Good luck!
CodePudding user response:
If your component is functional component then you can pass the Type to it like below:
const YourComponent: React.FC<React.HTMLProps<Element>> = (props => {---your component code---})