簡體   English   中英

更改道具時如何使React組件獲取數據

[英]How to make react component fetch data when props is changed

我正在嘗試更改道具時重新渲染我的組件並獲取新數據,但是我無法使其工作。

export default class InfoTagEditor extends React.PureComponent<Props, State> {
    componentDidUpdate() {
        $.get('/webapi/getData?componentId=' + this.props.id, function (data) {
            this.setState({value: data});
            this.initComponentsDropdownlist();
        }.bind(this));
    }
}

但這根本不會更新狀態...

有人知道怎么了嗎?

渲染功能中的Kendo編輯器:

Render(){
    return   <Editor
    name={"Editor"}
    value={this.state.value}
    change={this.onChangeEditor}
    resizable={true}
    />
}

對我有用的是:

shouldComponentUpdate(nextProps)
{
    if (this.props.Id !== nextProps.Id) {
        $.get('/webapi/GetData?Id=' + nextProps.Id, function (data) {
            this.setState({value: data});
            $('#editor').data('kendoEditor').value(this.state.value)
            return true;
        }.bind(this));
    }

    if (this.props.name !== nextProps.name) {
        return true;
    }

    return false;
}

但這是這樣做的正確方法嗎? Id和Name是對應的,這意味着每當有一個新的ID時,也將有一個新的Name。

我應該分開做嗎

this.setState({ value: data });
$('#editor').data('kendoEditor').value(this.state.value)

要么

 this.setState({ value: data },  
 $('#editor').data('kendoEditor').value(this.state.value)); 

設法完成了這項工作:

componentDidUpdate(prevProps) {
    if(this.props.id!== prevProps.id) {
        $.get('/webapi/GetData?id=' + this.props.id, function (data) {
            this.setState({ editorValue: data }, $('#editor').data('kendoEditor').value(data)); 
        }.bind(this));
     }
}

這是進行回調的正確方法嗎? 看起來還好嗎? :)還是應該將$('#editor')。data('kendoEditor')。value(data)移到setState之外?

首先,您應該添加一個條件以防止無限循環( setState -> componentDidUpdate -> setState -> componentDidUpdate .... ): https : //reactjs.org/docs/react-component.html#componentdidupdate

您可以在componentDidUpdate()中立即調用setState(),但請注意,必須將其包裝在如上例中所示的條件下,否則會導致無限循環

這是一個可能的解決方案

componentDidUpdate(prevProps) {
    if(this.props.id !== prevProps.id) {
        $.get('/webapi/getData?componentId=' + this.props.id, (data) => {
           this.setState({ value: data });
           this.initComponentsDropdownlist();
        });
     }
}

請注意,如果initComponentsDropdownlist方法使用this.state.value ,則應在setState完成時調用它,因此應替換:

this.setState({ value: data });
this.initComponentsDropdownlist();

通過

 this.setState({ value: data }, this.initComponentsDropdownlist);

使用componentWillReceiveProps

export default class InfoTagEditor extends React.PureComponent {        
   componentWillReceiveProps(props)
   {
           $.get('/webapi/getData?componentId=' + props.id, function (data) 
           {
                this.setState({ value: data });
                this.initComponentsDropdownlist();
            }.bind(this));
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM