如何使用react更改变量状态?

时间:2019-05-22 08:28:46

标签: javascript reactjs react-native state setstate

我的状态上有一个user_id,看起来像是:

this.state ={id_user:''}

我想从另一个组件获取此id_user,我这样开发它:

handleAjouter = (id_user) => {
    this.setState({
      openPopupAjout: true,
      id_user: id_user
    });
    console.log(id_user, this.state.id_user)
  }

当我运行它时,我进入了控制台:

  • id_user: 1258

  • this.state.id_user: it's empty value

但是当我将方法handleAjouter更改为此时:

handleAjouter = (id_user) => {
    this.state.id_user = id_user;
    this.setState({
      openPopupAjout: true
    });
    console.log(id_user, this.state.id_user)
  }

我进入控制台:

  • id_user: 1258

  • this.state.id_user: 1258

但是,我也得到了Do not mutate state directly. Use setState()

我该如何解决?

0 个答案:

没有答案