【问题标题】:Calling a parent function from child gets called but doesn't change the state从子调用父函数被调用但不会改变状态
【发布时间】:2019-12-12 04:37:03
【问题描述】:

我正在开发一个 React Native 应用程序,我正在从子组件调用父函数,它被调用但它不会改变状态。基本上我正在从子打开一个模态,并希望通过更改模态上的某些内容来更改父组件的状态并关闭模态。

这是父级:

constructor(props) {
super(props);
this._toggleModal = this._toggleModal.bind(this)
this.state = {
  isActive: false}}                             

  _toggleModal = async() => {
    this.setState({ isModalVisible: !this.state.isModalVisible })
  }

  doSomthing(x) {
    console.log(x)
    this._toggleModal;
  }

   render() {
    return (
     <RateModal toggleCall1={this.doSomthing}/>
     )}

这是孩子:

  ratingCompleted = async(rating)=> {
    console.log("Rating is: " + rating)
    await this.props.toggleCall1(false)
  }

在这里,当给出评分时,我从孩子那里获得了false 道具,但它不会改变父母的状态。如何解决?

【问题讨论】:

  • 如果我这样做。_toggleModal();然后它显示未处理的承诺拒绝,并且 this._toggleModal() 不是一个函数。
  • 你在构造函数中绑定了doSomthing()吗?
  • 我已经更新了这个问题。我确实像更新的问题一样绑定。
  • 不,你没有。你绑定了_toggleModal,它甚至不需要绑定,因为它是一个箭头函数。需要绑定doSomthing或者变成箭头函数。

标签: react-native


【解决方案1】:

试试这个

doSomthing = (x) => {
  console.log(x)
  this._toggleModal();
}

您要么需要绑定此上下文,要么将函数更改为箭头函数

【讨论】:

    【解决方案2】:

    你需要调用函数,

    this._toggleModal()
    

    【讨论】:

    • 如果我这样做。_toggleModal();然后它显示未处理的承诺拒绝,并且 this._toggleModal() 不是函数。
    • 你需要将 this 绑定到构造函数中的 doSomthing 函数 like-this.doSomthing = this.doSomthing.bind(this)
    • 同时从子组件函数中移除异步等待。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-12
    • 2021-01-13
    • 1970-01-01
    • 2021-03-14
    • 2011-09-08
    • 1970-01-01
    相关资源
    最近更新 更多