我正在尝试用 React 中使用 setState 的函数生成的数组替换最初为空的数组。我的构造函数中有如下内容:
this.state = {
sources: []
};
这显示了正确的数组(我用 [0,1,2] 测试了它)。但是,当我尝试以这样的方法设置状态时:
this.setState({
sources: [0,1,2]
})
它不起作用并且仍然显示空(或原始)数组。我知道你不能直接在 React 中改变数组作为状态,但我不认为这就是我在这里所做的。以下是我在研究这个问题时尝试过的其他一些方法,但都没有奏效:
this.setState({
sources: [...this.state.sources, 1]
})
...
this.setState({
sources: this.state.sources.concat('test')
})
...
var temp = [0,1,2]
this.setState({
sources: temp
})
在此先感谢您的帮助!
编辑完整代码:
export class SrcMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
sources: [],
};
this.searchSources = this.searchSources.bind(this);
}
searchSources() {
// commented out the actual method to replace with test code
var temp=[0,1,2];
console.log(temp); // [0,1,2] so I know the method works
this.setState({
sources: temp // etc for the other things i tried
})
console.log("this.state.sources: " + this.state.sources); // empty
}
render() {
return(
// etc...
<button type="button" onClick={this.searchSources}>Test</button>
);
}
}
最佳答案
您的代码可以正常工作,但您没有考虑到 setState
是异步的。如果您在可以作为 setState
的第二个参数的回调中记录 this.state
,它将保证它已更新。
this.setState({ sources: temp }, () => {
console.log(this.state.sources);
});
关于javascript - 在 React 中使用数组设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51383597/