我已经尝试了两个类组件:
class Foo extends React.Component { x = 3; componentDidMount () { fetch(apiURL).then(() => { x = 5; }); } render () { return <div>{x}</div>; } }
并使用功能组件:
let x = 3; fetch(apiURL).then(() => { x = 5; }); const Foo = () => <div>{x}</div>;
页面上显示的x值永远不会改变,或者似乎是随机改变的。是什么赋予了?
当您告诉React某些更改时,React仅知道使用其为状态管理提供的功能来重新渲染:
class Foo extends React.Component { // In class components state must be an object state = { x: 3, }; componentDidMount () { fetch(apiURL).then(() => { // Note that we change state with the setState method. this.setState({ x: 5 }); }); } render () { return <div>{this.state.x}</div>; } }
另外,功能组件应该是 纯 组件(没有副作用),因此要更新它们,React会给我们带来麻烦:
const Foo = () => { const [x, setX] = useState(3); useEffect(() => { fetch(apiURL).then(() => { // We use the setter returned from useState. setX(5); }); }, []); return <div>{x}</div>; }
因此,您不能只是分配给一个变量并期望React知道:您必须使用它的更新函数,以便它知道需要将数据重新呈现到页面。