如何在加载特定子组件时通知React父组件

时间:2017-09-25 16:36:01

标签: javascript reactjs setstate

我有一个文本输入组件,它包含以下HOC组件withSticky。 withSticky确定组件是否是粘性字段。如果是,我希望父组件知道。但是,我希望父组件更新某些状态。一切都很好,但这也会导致无限循环,因为我将回调放在componentDidMount和setState中,导致所有子组件重新渲染自己 - 重新生成生命周期。我不想在每种情况下都寻找这些类型的动态字段,因为它们并不总是被使用。

我现在不使用redux只是简单的setState。

  import React from 'react';

const withSticky = (Component) => {
    return class extends React.Component {        
        constructor(props) {
            super(props);
            Component.displayName = 'withStickyContainer';
        }
    componentDidMount() {        
        const { fieldMetadata, onSticky,field} = this.props;
        //here fieldMetadata is not populated. therefore
        //fieldMetadata.IsSticky is undefined and onSticky never fires.
        const IsSticky = fieldMetadata.IsSticky;  
            console.log("is sticky mounted : ", this.props);
        if(IsSticky)
           onSticky(field.Id,field.Value);
    }
    render() {
     //wrong place to check field and trigger callback. This was calling infinite loop. Updated and moved to componentDidMount.
     //const { fieldMetadata, onSticky,field} = this.props;                        
     //const IsSticky = fieldMetadata.IsSticky;  
       // if(IsSticky)
         //  onSticky(field.Id,field.Value);
        console.log("field is sticky");          
        return (
            <div>
                <Component {...this.props}   />                    
            </div>
        );
    }
    }
};
export default withSticky;

将从子组件的props中触发的父组件内的方法。

    onSticky(fieldId,fieldValue){
    console.log("onsticky fired:",fieldId);
    console.log("field value : ", fieldValue);
    console.log("is field empty: ", _trim(fieldValue) ==='');
    const IS_EMPTY =_trim(fieldValue) ==='';
    const NOT_FOUND = -1;
    //lookup field Id and populate
    //check if lookup has value already if it does than update this field with value in lookup table
    //else take current value at set as initial sticky value.
    const {stickyFields} = this.state;        
    const foundField = _findIndex(stickyFields,f=> { f.Id == fieldId});
    if( foundField === NOT_FOUND && IS_EMPTY ){
        console.log("found nothing doing nothing");
        return;
    }else if(foundField === NOT_FOUND && !IS_EMPTY){
        //add to stickyFields lookup table.
        let stickyFieldsClone = deepClone(stickyFields);
        stickyFieldsClone.push({Id:fieldId,value:fieldValue});
        console.log("updating sticky fields lookup table");
        this.setState({stickyFields:stickyFieldsClone});
    }else if( foundField !== NOT_FOUND ){
        //grab value from lookup table and update field value 
    return;
    }        
}

简而言之,我在父组件中有一个数据结构,可以跟踪所有这些粘性字段。我不想搜索它们,但我希望在用户使用它们时得到通知。如果使用它们,则跟踪该字段内的值。

0 个答案:

没有答案