简体   繁体   English

React状态变量在渲染方法中未定义

[英]React state variable is undefined inside render method

I have a state variable dataSource that has some data in it. 我有一个状态变量dataSource ,其中包含一些数据。

In a parent component I have the following: 在父组件中,我具有以下内容:

updateFeed = newItem => {
    this.setState({ dataSource: this.state.dataSource.data.unshift(newItem) })
    console.log(this.state.dataSource.data)
  }
  render() {
    console.log(this.state.dataSource.data)
    return (
      <React.Fragment>
        <Header />
        <Route
          path="/"
          exact
          component={props => (
            <Feed {...props} feedData={this.state.dataSource.data} updateFeed={this.updateFeed} />
          )}
        />
        <Route path="/profile/:id" exact component={props => <Profile {...props} />} />
      </React.Fragment>
    )
  }

updateFeed is called from the child component. 从子组件调用updateFeed

onSubmit = () => {
    const newPost = newData // some new data
    this.props.updateFeed(newPost)
  }

The updateFeed function is getting executed on submit, and the console.log is giving the updated data. updateFeed函数将在提交时执行, console.log将提供更新的数据。 But inside the render function this.state.dataSource.data is undefined . 但是在渲染函数中this.state.dataSource.dataundefined What am I missing here? 我在这里想念什么?

You do dataSource: dataSource.data in your setState call, therefore dataSource.data in your render method will actually access dataSource.data.data which is probably undefined. 你做dataSource: dataSource.data在你的setState通话,因此dataSource.data在渲染方法将实际访问dataSource.data.data这可能是不确定的。 May change updatedFeed to: 可能将updatedFeed更改为:

 updateFeed = newItem => {
    this.setState(prev => ({
       dataSource: {
           ...prev.dataSource,
           data: prev.dataSource.data.concat(newItem)
       }
    }));      
  }

Which ensures a pure state. 这确保了纯状态。

It is because previously, this.state.dataSource is an object having key data . 这是因为以前, this.state.dataSource是具有key data的对象。 So even you are setting new value in updateFeed but in the very next line, state has not been updated yet. 因此,即使您在updateFeed中设置新值,但在下一行中,状态尚未更新。 React does this asynchronously. React异步地做到这一点。 so your log statement is showing old data. 因此您的日志语句显示的是旧数据。

You need to update state like this 您需要像这样更新状态

const dataSource = this.state.dataSource;
dataSource.data.unshift(newItem);
this.setState({ dataSource: dataSource })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM