首页 > 解决方案 > 可以在 React 中像这样在 setState 中进行回调吗?

问题描述

我现在要做出反应,我想知道我所做的是否是创建此组件的不好方法。我想知道的是:这是在 setState 中进行回调的正确方法吗?如果没有,这行 $('#editor').data('kendoEditor').value(data) 应该放在哪里?

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

为什么这不起作用?

componentDidMount() {
    this.initEditor();
    $.get('/webapi/GetData', function (data) {
        this.setState({ data: data });
    }.bind(this));
}


 initEditor = () => {
        $("#editor").kendoEditor({ 
            value: this.state.editorValue,
        )}
    }

但这有效吗?

componentDidMount() {
    $.get('/webapi/GetData', function (data) {
        this.setState({ data: data });
        this.initEditor();
    }.bind(this));
}

标签: reactjs

解决方案


要在 setState 之后正确执行回调,请遵循以下格式:

this.setState( { foo: bar }, () => callbackFunction() )

编辑

要回答问题的第二部分,您根本不需要使用这些代码行。让 React 处理渲染。假设你有这样的渲染

render() {
    return(

        <div>
            <input type="text" name="someValue" data-kendoeditor={this.state.editorValue} />
        </div>

    )
}

然后像这样调用 setState:

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

这会将值从状态重新渲染到 DOM。


推荐阅读