简体   繁体   English

React Native-setState在构造函数中不起作用

[英]React Native - setState doesn't work in constructor

Here is my code: 这是我的代码:

I want to set functions results which I get them as promises to some state variables but as it seems after use this.setState in then() function it returns empty object! 我想设置函数结果,将它们作为对某些状态变量的承诺,但是在then()函数中使用this.setState之后,它似乎返回空对象! I checked in then() block and it contains data as it's supposed to. 我检查了then()块,它包含了应该包含的数据。

class ProfileScreen extends Component{
    constructor(props){
        super(props);

        this.state = {
            profile_data: {},
            user_data: {}
        };

        this._getUserData().then(response => {
            this.setState({user_data: response});
        });
        //Empty Results
        console.log(this.state.user_data);

        this._getProfileData(this.state.user_data.id).then(response => {
            this.setState({profile_data: response});
        })
    }
}

First of all you should never set your state in constructor using setState as a call to setState leads to rerendering of the view heirarchy which is not yet built to be rerendered. 首先, 永远不要在使用setState的构造函数中设置状态,因为对setState的调用会导致重新渲染尚未构建的视图层次结构。

A better place for doing so is componentDidMount because thats a lifecycle callback which ensures that the DOM is already rendered once and now you can update your state to see the changes in the view. 更好的方法是componentDidMount因为这是一个生命周期回调,可确保DOM已经被渲染一次,现在您可以更新状态以查看视图中的更改。

Coming to your problem, the empty result is due to the fact that the setState is asynchronous in nature, thus the console.log would have run even before the setState has updated the state. 对于您的问题,空结果是由于setState本质上是异步的,因此,即使setState更新了状态, console.log也会运行。

You should rely on the second parameter of the setState which is a callback that runs post the state update. 您应该依赖setState的第二个参数,该参数是在状态更新后运行的回调。

this.setState({
   user_data: response
}, () => {
    console.log(this.state.user_data);
})

Don't do this in your constructor. 不要在构造函数中执行此操作。 Fetch your user detail in componentDidMount and then set your state as per your need componentDidMount获取用户详细信息,然后根据需要设置状态

In addition to what Suraj said, if _getUserData is asynchronous, perhaps doing an AJAX call, then _getProfileData must be inside the .then callback too since you depend on the user_data to fetch the profile_data . 除了Suraj所说的以外,如果_getUserData是异步的,也许正在执行AJAX调用,则_getProfileData必须位于_getProfileData回调内部.then因为您依赖于user_data来获取profile_data

Try this snack out: https://snack.expo.io/@transfusion/stackoverflow-53694220 试试这个小吃: https : //snack.expo.io/@transfusion/stackoverflow-53694220

It might be cleaner to just chain the promises together. 仅将承诺链接在一起可能会更清洁。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM