为什么 React 不能正确呈现我的组件状态?

IT技术 javascript reactjs
2021-03-19 10:12:41

我已经用类组件尝试过这个:

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 值永远不会改变,或者似乎是随机改变的。是什么赋予了?

1个回答

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 知道:你必须使用它的更新函数,所以它知道它需要重新渲染该数据到页面。