【问题标题】:How to access a current state in another component?如何访问另一个组件中的当前状态?
【发布时间】:2018-02-01 19:35:49
【问题描述】:

我正在尝试在另一个组件中访问此用户集。我使用此函数从最高组件(即应用程序)向下传递状态以更改状态。

  handleRegisterSubmit(e, username, password) {
    e.preventDefault();
    axios.post('/auth/register', {
      username,
      password,
    }).then(res => {
      console.log(res.data.user.id)
      this.setState({  
        auth: res.data.auth,
        user: res.data.user,
        currentPage: 'selectSources',
      });
    }).catch(err => console.log(err));
  }

在后端命中模型后,它会返回一个响应,在该响应中我将用户状态从 null 更改为包含用户信息的对象。

然后我将该信息传递给主组件。

renderHomeIfloggedin(){
  if (this.state.auth){
    console.log(this.state.user)
    return  <Home auth={this.state.auth} userInfo={this.state.user}/>
  }
}

在 home 组件中我点击了这个函数

renderSelectSources(){
    if (!this.state.dataLoaded){
      console.log(this.props.userInfo,'djfosidjfodisj')
        return (
     <div>
       {this.props.user}
       <SelectSources user={this.props.userInfo} test={this.returnSources}/>
       </div>)
    }
}

然后我尝试使用道具从应用程序组件访问用户对象。并将其传递给 Selectsources 组件。

在选择源组件内部,我想将新闻对象与用户对象一起发布并将其发送到后端。新闻对象发送良好,但我正在努力访问当前状态。当我查看 react 开发人员工具时,用户状态是我想要的信息,但是当我出于某种原因控制台记录它时,道具信息是未定义的。

handleClick(source_object) {
  console.log(source_object,'ioefjsoejfoi',this.props.user);
  axios.post('/news', {
    source: source_object,
  })
  .then(res => {
    console.log("Posted"+ source_object.source.name);
    console.log(res);
  })
  .catch(err => console.log(err));

屏幕截图显示用户对象仍然是当前状态,所以我不确定我哪里出错了。

【问题讨论】:

  • 您有两个与同一事物相关的道具,useruserInfo。检查是否有错别字

标签: javascript node.js reactjs react-native react-router


【解决方案1】:

看来你的问题是关于this 在方法handleClick 中的内容,按其名称,我假设该方法是按下按钮时的某种回调,因此当单击时调用该方法事件 this 对象不再指向 SelectSources 类的 this(您的 userInfo 所在的位置)

要解决此问题,您必须在 SelectSources 类的构造函数中绑定方法

class SelectSources extends Component {
  constructor(props){
    super(props);

    // Make sure the handleClick method is always pointing to the this of this class
    this.handleClick = this.handleClick.bind(this); 
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-20
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 2022-11-27
    相关资源
    最近更新 更多