如何访问另一个组件中的当前状态?

时间:2017-08-24 04:10:48

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

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

  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}/>
  }
}

在主页组件中我点击了这个功能

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>)
    }
}
然后我尝试使用props从app组件访问用户对象。并将其传递给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));

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

enter image description here

1 个答案:

答案 0 :(得分:0)

似乎你的问题是关于方法this中的handleClick,它的名称我假设方法是按下时按钮的某种回调,所以当该方法是调用click事件时,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); 
  }
}
相关问题