【发布时间】:2017-02-13 06:24:44
【问题描述】:
constructor(props) {
this.state = {contents: []};
}
componentDidMount() {
var self = this;
console.log('> Manage mounted');
ServerService.getServers(
Parse,
self.props.parentState.state.activeAccount,
(error, results) => {
if (error) {
throw new Error(error);
}
this.setState((prevState, props) => ({
contents: results
}));
}
);
}
您好,我上面有这段代码。我有一个名为 Manage and Servers 的组件。现在,从安装 Manage 组件开始,我想通过 ServerService.getServers() 填充它的 this.state.contents。该实用程序返回一个results,它是一个来自回调函数的数组。但是,状态没有进入。这是从回调函数中更新组件状态的正确方法吗?
此外,我将上述状态传递给名为 MainContent 的子组件,例如<MainContent contents={this.state.contents} />,并在组件安装时将其视为道具
componentDidMount() {
console.log('> MainContent is mounted');
console.log(this.props.contents);
}
问题是,来自MainContent 组件的this.props.contents 仍然是一个空白数组。我这样做的原因是因为我进一步使用了contents 中的值,作为MainContent 子组件的另一组props。
【问题讨论】:
标签: javascript reactjs