Javascript Can';t更新组件';回调函数中的状态
你好,我有上面的代码。我有一个名为Manage和Servers的组件。现在,从安装Manage组件时起,我就想通过Javascript Can';t更新组件';回调函数中的状态,javascript,reactjs,Javascript,Reactjs,你好,我有上面的代码。我有一个名为Manage和Servers的组件。现在,从安装Manage组件时起,我就想通过ServerService.getServers()来填充this.state.contents。该实用程序返回一个结果,它是回调函数中的一个数组。不过,州政府并没有参与进来。这是从回调函数中的更新组件状态的正确方法吗 此外,我正在将所述状态传递给名为MainContent的子组件,例如,并在安装组件时将其视为道具 constructor(props) { this.stat
ServerService.getServers()
来填充this.state.contents。该实用程序返回一个结果
,它是回调函数中的一个数组。不过,州政府并没有参与进来。这是从回调函数中的更新组件状态的正确方法吗
此外,我正在将所述状态传递给名为MainContent
的子组件,例如
,并在安装组件时将其视为道具
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
}));
}
);
}
问题是,
this.props.contents
fromMainContent
组件仍然是一个空白数组。我之所以这样做,是因为我进一步使用了contents
中的值,作为MainContent
子组件的另一组props
。当您尝试更新类似的状态时,您用于更新状态的方法在场景中非常有用
componentDidMount() {
console.log('> MainContent is mounted');
console.log(this.props.contents);
}
i、 e利用先前的状态
以及道具
,因为this.props
和this.state可能会异步更新,所以您不应该依赖它们的值来计算下一个状态
但是,您在函数内部使用setState,因此这里的这个
关键字不会引用正确的内容,您也应该使用self
,因为您正在使用不依赖于状态或道具的值更新状态,因此您可以使用直接方法更新状态,如
this.setState((prevState, props) => ({
contents: [...prevState.content, props.content]
}));
代码:
self.setState({contents: results});
至于在MainContent
的componentDidMount
中获取空白数组,您将获得一个空白数组,因为componentDidMount仅在初始渲染时呈现,并且在初始渲染时,您的this.state.contents
是一个空白数组,因此您将获得一个空值
将其更改为componentWillReceiveProps
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
});
}
);
}
嗨@Shubham,谢谢你的回答。对不起,我还有其他问题要问。我更新了上面的问题。@TeodyC.Seguin更新了您进一步询问的答案谢谢@Shubham,这真的很有帮助。我正在获取填充阵列。很好,很高兴能提供帮助
componentWillReceiveProps(nextProps) {
console.log("Main content");
console.log(nextProps.contents);
}