从子组件更改父状态无效

时间:2019-04-23 12:25:45

标签: javascript reactjs

我有家长部分:

state = {
   value: 0
}

add() {
   let { value } = this.state

   value++

   this.setState({ value: value})
}

remove() {
   let { value } = this.state

   value--

   this.setState({ value: value})
}

render() {
   return(
      <Child add={this.add} remove={this.remove} />
   )
}

和子组件:

...

render() {
   const { add, remove } = this.props

   return(
      <div>
         <button onClick={() => add()}>Add</button>
         <button onClick={() => remove()}>Remove</button>
      </div>
   )
}

当我单击子组件内的按钮时,我想更新父组件中的value状态。但是,当我尝试以这种方式执行此操作时,会收到错误消息:

  

无法读取未定义的属性“状态”

我做错了什么?预先感谢。

4 个答案:

答案 0 :(得分:1)

  <Child add={this.add.bind(this)} remove={this.remove.bind(this)} />

喜欢

答案 1 :(得分:1)

出现问题是因为您的方法失去了与this的绑定。有两种解决方法。

箭头功能

使用es6,您可以使用arrow functions来定义与this自动绑定的函数,如下所示:

add = () => {
   let { value } = this.state

   value++

   this.setState({ value: value})
}

remove = () => {
   let { value } = this.state

   value--

   this.setState({ value: value})
}

绑定功能

在组件的constructor中,您可以使用bind函数来指定显式绑定,如下所示:

constructor(props) {
  super(props);
  this.add = this.add.bind(this);
  this.remove = this.remove.bind(this);
}

答案 2 :(得分:1)

您必须绑定方法或使用箭头功能。与常规函数不同,箭头函数不会对此进行绑定。相反,这在词汇上受约束。保留了原始背景的含义

export class SomeComponent extends React.Component {
    constructor(props) {
        super(props);
        this.remove = this.remove.bind(this);
        this.add = this.add.bind(this);
    }

    add() {
     let { value } = this.state

      value++

      this.setState({ value: value})
    }

   remove() {
      let { value } = this.state

      value--

      this.setState({ value: value})
   }
    // arrow function
    someFuncion = () => {
     this.setState({ value: 0})
    }
}

答案 3 :(得分:0)

使用粗箭头获取函数内部的this参考。
就您而言,

state = {
   value: 0
}

add = () => {
   let { value } = this.state

   value++

   this.setState({ value: value})
}

remove = ()=> {
   let { value } = this.state

   value--

   this.setState({ value: value})
}

render() {
   return(
      <Child add={this.add} remove={this.remove} />
   )
}
相关问题