状态更改后,ReactJS元素不会重新加载

时间:2018-12-14 04:49:57

标签: javascript reactjs

反应状态改变真的很快的问题。

我有一个状态departments: [],它将在componentDidMount上接收值。 在render()中,我使用map function显示该数组中的所有项目。

问题是,第一次加载页面时,状态departments尚未完全加载,但是一旦加载,页面就不会为该特定元素呈现。

代码:

componentDidMount: function() {
    helpers.getAllDepartments().then(function(response){
        if (response !== this.state.departments) {
        this.setState({
            departments: response.data.department

        }, this.getOptions());
        }
    }.bind(this));
}
getOptions: function() {
    this.setState({
        isLoaded: true
    })
},

在渲染中:

{
(this.state.isLoaded) ? this.state.departments.map((each, i) => {
return(
<option key={i} value={each}>{each}</option>
)
}) : <option>Nothing</option>
}

结果显示Nothing。当console.log(this.state.departments)时。它显示4次。 第一个为空白,但是从第二个开始为空白。

更新 我测试过

 {(this.state.isLoaded)?<b>loaded</b>:<b>not loaded</b>}

结果为loaded。但是array map function不会更新。

2 个答案:

答案 0 :(得分:2)

为什么要使用回调getOptions来设置外部状态的一半?您可以在单个setState调用中组合状态更改,如下所示:

componentDidMount: function() {
    helpers.getAllDepartments().then(function(response){
        if (response !== this.state.departments) {
        this.setState({
            departments: response.data.department,
            isLoaded: true
        });
        }
    }.bind(this));
}

答案 1 :(得分:0)

由于某些原因,我在Selection DOM中添加了一个className,它可以工作。