为什么React无法正确呈现我的组件状态? [英] Why is React not rendering my component state correctly?

查看:47
本文介绍了为什么React无法正确呈现我的组件状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've tried this with both a class component:

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值永远不会改变,或者似乎是随机改变的.有什么作用?

And the value of x shown on the page never changes, or seems to change randomly. What gives?

推荐答案

仅当您告诉它某些更改时,React才知道要重新渲染,方法是使用它提供的状态管理功能:

React only knows to re-render when you tell it something changed, by using the facilities it provides for state management:

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>;
    }
}

其他功能组件应该是 pure (没有副作用),因此要更新它们,React会给我们带来麻烦:

additionally function components should be pure (no side-effects) so to update them React gives us hooks:

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

So you can't just assign to a variable and expect React to know: you have to use it's update functions so it knows it needs to re-render that data to the page.

这篇关于为什么React无法正确呈现我的组件状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆