[英]Can't update a component's state inside a callback function
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组件开始,我想通过ServerService.getServers()
填充它为this.state.contents。 该实用程序返回results
,该results
是回调函数的数组。 但是,状态并没有进入。这是从回调函数中更新组件状态的正确方法吗?
此外,我将上述状态传递给名为MainContent
的子组件,例如<MainContent contents={this.state.contents} />
,并在安装组件时将其作为道具观看
componentDidMount() {
console.log('> MainContent is mounted');
console.log(this.props.contents);
}
事实是, MainContent
组件中的this.props.contents
仍然是一个空白数组。 为什么我这样做的原因是因为我有在价值的进一步使用contents
,作为另一组的props
进行MainContent
子组件。
在尝试更新状态之类的情况下,用于更新状态的方法很有用
this.setState((prevState, props) => ({
contents: [...prevState.content, props.content]
}));
即使用先前的state
和props
因为this.props
和this.state可能会异步更新,因此您不应依赖于它们的值来计算下一个状态。
然而,你使用的是函数内部的setState,因此this
位置的关键字不会指向正确的内容,你应该利用self
也因为您正在使用不依赖于国家或道具的值更新状态,因此你可以使用更新状态的直接方法
self.setState({contents: results});
码:
componentDidMount() {
var self = this;
console.log('> Manage mounted');
ServerService.getServers(
Parse,
self.props.parentState.state.activeAccount,
(error, results) => {
if (error) {
throw new Error(error);
}
self.setState({
contents: results
});
}
);
}
就在MainContent
componentDidMount
中获取空白数组而言,您将获得一个平淡的数组,因为componentDidMount仅在初始渲染时渲染,并且由于在初始渲染时this.state.contents
是一个空白数组,因此您会得到一个空值。
将其更改为componentWillReceiveProps
componentWillReceiveProps(nextProps) {
console.log("Main content");
console.log(nextProps.contents);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.