我刚开始学习 React,我想知道为什么下面的代码不能按预期工作。我以为它会显示 The numbers: 0123
但它只显示 0
。我也对基于类的组件使用了相同的方法,并使用了钩子(Hook),但我仍然得到相同的结果。我对使用异步代码进行 react 渲染有什么不理解的?
import React from "react";
import ReactDOM from "react-dom";
function App() {
let numbers = [0];
fetch("some.url")
.then(res => res.json())
.then(list => {
for (let n of list) {
numbers.push(n);
}
});
return <div className="App">The numbers: {numbers}</div>;
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
最佳答案
您的代码打印 0,因为它是渲染时变量 number
的值。
您使用以下代码:
fetch("some.url")
.then(res => res.json())
.then(list => {
for (let n of list) {
numbers.push(n);
}
});
异步获取新值,但不会有任何效果:组件已经渲染。
如果你想刷新它,你必须把你的变量号放在state
中,然后使用setState()
来传递新值。
如果你想保持功能组件,你应该使用全新的钩子(Hook)特性,它应该给你等效于 setState
。
关于javascript - 了解异步 React 渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55142538/