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组件开始,我想通过填充它为this.state.contents ServerService.getServers()。该实用程序返回a results,它是回调函数的数组。但是,状态并没有进入。这是从回调函数中更新组件状态的正确方法吗?
ServerService.getServers()
results
此外,我将上述状态传递给名为MainContent例如的子组件<MainContent contents={this.state.contents} />,并在安装该组件时将其作为道具观看
MainContent
<MainContent contents={this.state.contents} />
componentDidMount() { console.log('> MainContent is mounted'); console.log(this.props.contents); }
问题是,this.props.contents从MainContent组件开始仍然是一个空白数组。之所以这样做,是因为我进一步将中的值用作子组件的contents另一组。props``MainContent
this.props.contents
contents
props``MainContent
在尝试更新状态之类的情况下,用于更新状态的方法很有用
this.setState((prevState, props) => ({ contents: [...prevState.content, props.content] }));
即,利用前一个state以及props因为this.props和this.state可以异步更新,您不应依赖于它们的值来计算下一个状态。
state
props
this.props
但是,您在函数内部使用setState,因此this此处的关键字将无法引用正确的内容,您还应使用,self因为您正在使用不依赖于状态或道具的值来更新状态,因此可以使用直接更新状态的方法
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 }); } ); }
至于获得一个空白阵列componentDidMount的MainContent来讲,你会因为componentDidMount只呈现初始呈现,并且因为在最初会使您得到一个平淡无奇的阵列this.state.contents是一个空白阵列,你会得到一个空值。
componentDidMount
this.state.contents
更改为 componentWillReceiveProps
componentWillReceiveProps
componentWillReceiveProps(nextProps) { console.log("Main content"); console.log(nextProps.contents); }