繁体   English   中英

使用作为道具传递给子代的函数更新父状态

[英]Updating Parent state with function passed as prop to Child

一旦ChildForm调用作为prop传递的函数,我想刷新Parent组件的状态。 我的组件的结构如下。

class Parent extends React.Component {
    constructor() {
        super();
        this.state = {data: []};
    }

    getThings() {
        //Working ajax get request for data
    }

    updateThing(obj){
        $.ajax({
          url: `/api/update/${obj.identifier}`,
          dataType: 'json',
          type: 'POST',
          data: obj,
          success: (res) => {
              this.getThings();
          },
          error: (xhr, status, err) => {
            console.error(`/api/update/${obj.identifier}`, status, err.toString());
          }
        });
    }

    componentDiMount() {
        this.getThings();
    }

    render() {
        let childForms = this.state.data.map((x, i) => {
            return (
                <ChildForm key={i} id={`thing${i}`} {...x} update={this.updateThing} />
            );
        });
        let dataVisuals = this.state.data.map((x, i) => {
            return (
                <DataViz key={i} {...x} />
            );
        });
        return (
            <div>
                {dataVisuals}
                {childForms}
            </div>
        );
    }
}

class ChildForm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {...props};
        this.handleUpdate = this.handleUpdate.bind(this);
    }
    handleInputChange() {
        ///working input functionality to update form state
    }
    handleUpdate() {
        let obj = {...this.state};
        this.props.update(obj);
    }
    render() {
        //Form for updating individual thing
    }
}

当ChildForm调用this.props.update时,记录在db上成功更新,但是我收到一个错误,指出this.getThings()不是函数,并且Parent组件没有更新。 如何在Parent上触发状态更新?

编辑 :对不起,忘记显示我有this.handleUpdate = this.handleUpdate.bind(this); ChildForm构造函数中。

发生了什么

尽管您this.updateThing传递给<ChildForm /> ,但是在update <ChildForm />调用此函数时,上下文已更改,这导致<ChildForm /> this.getThings()undefined

怎么修

在ChildForm中调用函数时,使用bind替换此方法。

来自MDN的报价:

bind()方法创建一个新函数,该函数在被调用时将其关键字设置为提供的值,并在调用新函数时提供给定的参数序列。

因此,尝试将update={this.updateThing}替换为update={this.updateThing.bind(this)}

暂无
暂无

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

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