【问题标题】:Why is React not rendering my component state correctly?为什么 React 不能正确渲染我的组件状态?
【发布时间】:2020-07-11 10:00:36
【问题描述】:

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

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

【问题讨论】:

标签: javascript reactjs


【解决方案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 知道:你必须使用它的更新函数,以便它知道它需要重新呈现该数据到页面。

【讨论】:

    猜你喜欢
    • 2021-08-06
    • 1970-01-01
    • 2020-03-30
    • 2021-05-28
    • 2018-01-09
    • 2021-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多