繁体   English   中英

从子组件更改父状态无效

[英]Change parent state from child component doesn't work

我有家长部分:

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状态。 但是,当我尝试以这种方式执行此操作时,会收到错误消息:

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

我做错了什么? 提前致谢。

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

像这样

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

箭头功能

使用es6,您可以使用箭头函数来定义与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);
}

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

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

使用粗箭头在函数内部获取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} />
   )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM