ReactJS:如何在State(useState)中获取响应数组,并在渲染/绑定时检查数组的长度



ReactJS:如何在State(useState(中获取响应数组,并在渲染/绑定时检查数组的长度。我不知道如何将recentData数组设置为useState来获得返回中的长度。

import React, { useState } from "react";
import UseData from "../../hooks/useData";
const HomePage = (props) => {
const [data, setData] = useState(false);

!data &&
UseData(formattedData => {
const { hasError, recentData } = formattedData;
console.log(recentData)  //// recentData has response 
if (hasError) {
//
} else {
setData(recentData); 
}
})

return (
// I want to get 'recentData' here like recentData.length > 0, have 'data' set true 
{data && data.map((info, i) => (   
<Grid key={i}>
member={info.firstName}
</Grid>
))}

// I want to get 'recentData' recentData.length === 1, 
{data &&
<Grid key={i}>
member={info.firstName}
</Grid>
))}
// I want to get 'recentData' recentData.length === 0

<Grid >
No data to render
</Grid>
)
}
export default HomePage
recentData array returned from the useData hook
0:
{firstName: "XXXX"
lastName: "YYYY"}
1:
{firstName: "AAAA"
lastName: "BBBBB"}
2:
{firstName: "CCCC"
lastName: "DDDD"}

我不知道如何将recentData数组设置为useState来获得返回中的长度。

您不需要做额外的工作就可以从状态中获取数组长度。如果您设置的状态data是一个数组,您只需在JSX中的任何位置使用属性.length来访问长度,您只需要{}就可以使用JavaScript代码。重要的是,您已经设置了默认数据false,一个布尔类型,它将在访问length的初始渲染时产生错误,所以将其设置为空数组,

const [data, setData] = useState([]);

让我们看一个例子:

const myComp = () => {
const [data, setData] = React.useState([]);
// do some stuff here to fetch data from anywhere and set it to data
return (
<>
{data.length === 0 ? <p>Length is 0</p>:null}
{data.length === 1 ? <p>Length is 1</p>:null}
{data.length > 1 ? <p>Length greater that 1</p>:null}
</>
)
}

相关内容

  • 没有找到相关文章

最新更新