environment:react 17.x、umi 3.5.21
In this code below, I send a request and build an array of components, using console.log(hosCardArr)
in then
has content
let hosCardArr: any[] = [];
useEffect(() => {
getHosList({ _location: location, _level: level }).then(function (
response: returnHosInfo[],
) {
let arr: any[] = [];
for (let i = 0; i < response.length; i ) {
let e: returnHosInfo = response[i]
if (i % 2 == 0) {
arr.push(<HosCard name={e.name} level={e.level} openTime={e.openTime} domLocation='left' />)
} else {
arr.push(<HosCard name={e.name} level={e.level} openTime={e.openTime} domLocation='right' />)
}
}
hosCardArr = arr
});
});
In this code below, I render the array, using console.log(hosCardArr)
in <div><div/>
the result is []
<div>{hosCardArr}</div>
The end result is that the elements in the array are not displayed
CodePudding user response:
The focus of this question is on data flow,If I don't use state
, it will render the array empty and not updated
const [hosCardArr, setHosCardArr] = useState<any[]>([]);
useEffect(() => {
getHosList({ _location: location, _level: level }).then(function (
response: returnHosInfo[],
) {
let arr: any[] = [];
for (let i = 0; i < response.length; i ) {
let e: returnHosInfo = response[i]
if (i % 2 == 0) {
arr.push(<HosCard name={e.name} level={e.level} openTime={e.openTime} domLocation='left' />)
} else {
arr.push(<HosCard name={e.name} level={e.level} openTime={e.openTime} domLocation='right' />)
}
}
setHosCardArr(arr)
});
}, []);
CodePudding user response:
you must use .map function to render each item of the array , like this :
return (
<>
{
hosCardArr.map((hos,index) =>
<div key={index}>{hos}</div>
);
}
</>
)