小编典典

为什么React无法正确呈现我的组件状态?

reactjs

我已经尝试了两个类组件:

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


阅读 264

收藏
2020-07-22

共1个答案

小编典典

当您告诉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知道:您必须使用它的更新函数,以便它知道需要将数据重新呈现到页面。

2020-07-22