useEffect and async()



useEffect()钩子中,我基本上是在尝试通过增加每次迭代中的lastIndex状态来为每个映射到tempData'item'对象添加一个'id'。但是,已映射的所有item.id都返回 0(初始状态值(。

我猜在迭代中调用setLastIndext函数有问题吗?谢谢。

const SearchAppointments  = React.memo(() => {

const [data, setData] = useState([ ])
const [lastIndex, setLastIndex] = useState(0)
useEffect( () => {
const fetchData = async() => {
var response = await fetch('../data.json');
var result = await response.json()
var tempData = result.map( item => {
item.id = lastIndex;
setLastIndex(lastIndex => lastIndex + 1);
return item
})
setData(tempData)
};
fetchData();
}, [])
return (
<div>
</div>
);
})
setLastIndex

是异步函数,lastIndex的值只会在下次渲染时更新,但result.map是同步函数==>lastIndex 始终为 0result.map

你可以试试这个:

const SearchAppointments  = React.memo(() => {
const [data, setData] = useState([ ])
// You not really need this lastIndex state for setting id for your data item, but somehow you want it after setData you can keep this and set to the last index of the item in fetched data
const [lastIndex, setLastIndex] = useState(0)
useEffect( () => {
const fetchData = async() => {
var response = await fetch('../data.json');
var result = await response.json()
var tempData = result.map( (item, index) => ({...item, id: index}))
setLastIndex(tempData.length -1)
setData(tempData)
};
fetchData();
}, [])
return (
<div>
</div>
);
})

你会试试这个:

const SearchAppointments  = React.memo(() => {
const [data, setData] = useState([]);
const fetchData = async() => {
const response = await fetch('../data.json');
const result = await response.json();
setData(result.map( (item, index) => ({...item, id:index})))
};
useEffect( () => {
fetchData();
}, [])
return (
<div>
</div>
);
})```

你真的需要lastIndex吗?

data.length. 它可以在内部使用setData(lastData=>...)

相关内容

  • 没有找到相关文章

最新更新