在其他反应组件中设置状态

时间:2018-05-09 13:48:34

标签: javascript reactjs

我关注了其他帖子,但无法修复。

我想从另一个组件中的一个组件设置状态。

这是我的最小例子:

function setOtherState(param1_new){
  this.setState({param1: param1_new})
}

export default class CompA extends React.Component {
  constructor(props) {
    super(props)
  }

  _setOtherState(param1_new) {
    updateShowThis(param1_new); // --> HERE I CALL THE METHOD IN THE OTHER COMPONENT!
  }

  componentDidMount() {
    this._setOtherState(true)
  }

  ...
}

class CompB extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      param1: false,
    }
    setOtherState = setOtherState.bind(this)
  }
  ...
}

AppRegistry.registerComponent('CompA', () => CompA);
AppRegistry.registerComponent("CompB", () => CompB);

然而,当我运行此代码时,我得到了:

  

TypeError:this.setState不是函数

如何正确设置另一个组件的状态?

1 个答案:

答案 0 :(得分:1)

您不应该直接从另一个组件设置setState()组件的状态。你的例子不起作用的原因是因为

function updateShowThis(show){
  this.setState({showThis: show})
}

在该函数this中没有引用任何组件(因为函数未在组件内定义)。但即使可以,如果您发现您正试图使用​​setState()直接从另一个组件操纵组件的状态,那么您需要重新访问组件层次结构并查看是否存在像Redux这样的状态管理工具可以解决您的问题。

相关问题