【发布时间】:2018-12-25 06:52:33
【问题描述】:
我正在尝试用 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>
);
}
}
【问题讨论】:
-
在这里工作 - codesandbox.io/s/l7j005yknz
-
构造函数中不应该是
this.state({ sources: [] };,而是this.state = { sources: [] }; -
你能发布一个你调用 setState 的方法的 sn-p
-
@Tholle 谢谢,这是我的问题中的错字,在实际的代码文件中我已经正确编写了
-
好的。您能否包括具有此行为的整个组件?很难说当前问题中的代码有什么问题。
标签: javascript arrays reactjs setstate