代码之家  ›  专栏  ›  技术社区  ›  Vladimir Humeniuk

从子组件更改父状态不起作用

  •  0
  • Vladimir Humeniuk  · 技术社区  · 6 年前

    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 当我单击子组件中的按钮时,父组件中的状态。但当我尝试这样做时,我收到了一个错误:

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

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

    4 回复  |  直到 6 年前
        1
  •  1
  •   Thomas Arbona    6 年前

    this . 有两种方法可以解决这个问题。

    箭头函数

    arrow functions 定义自动绑定的函数

    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
  •   Kishan Jaiswal    6 年前
      <Child add={this.add.bind(this)} remove={this.remove.bind(this)} />
    

    这样地

        3
  •  1
  •   henrik123    6 年前

    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})
        }
    }
    
    
        4
  •  0
  •   Engineer    6 年前

    使用粗箭头 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} />
       )
    }