状态改变不会重新渲染组件
const [list, setList] = useState([]);
useEffect(() => {
const getData = async () => {
let storeList = [];
for (let i = 0; i<50; i++) {
try {
const token = await contract.methods.tokenOfOwnerByIndex(accountId , i).call();
let data = await contract.methods.tokenURI(token).call();
const receivedData = await fetch(data);
let jsonData = await receivedData.json();
storeList.push(jsonData);
setList(storeList);
} catch(error) {
cogoToast.error(`Error caused in fetching data of ${i} number token`);
}
}
};
if (contract) getData();
}, [contract]);
“列表”的初始状态为空。当循环第一次运行并首次更新列表时,组件重新呈现,但是在此之后,即使状态更改组件也不会重新渲染。
理想情况下,当状态变化时,组件应重新渲染。
const [list, setList] = useState([]);
useEffect(() => {
const getData = async () => {
let storeList = [];
for (let i = 0; i<50; i++) {
try {
const token = await contract.methods.tokenOfOwnerByIndex(accountId , i).call();
let data = await contract.methods.tokenURI(token).call();
const receivedData = await fetch(data);
let jsonData = await receivedData.json();
storeList.push(jsonData);
setList(storeList);
} catch(error) {
cogoToast.error(`Error caused in fetching data of ${i} number token`);
}
}
};
if (contract) getData();
}, [contract]);
the initial state of "list" is empty. When the loop is run for 1st time and the list is updated for the first time, the component re-renders, but after that, even though the state is changing the component does not re-render.
Ideally, the component should re-render when the state changes.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在改变已经存在的数组,而不是创建一个新数组。当你在函数组件中设置状态时,react 会在旧状态和新状态之间执行
===
。如果它们相同,则会跳过渲染。要解决此问题,请创建一个新数组并使用该数组设置状态:
You're mutating the array that already exists, not creating a new one. When you set state in a function component, react does a
===
between the old state and the new state. If they're the same, it skips rendering.To fix this, create a new array and set state with that: