reactjs - 可以在 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));
}
解决方案
要在 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。
推荐阅读
- java - 如何在另一个线程上开始解析 Volley
- matlab - 通过 Jupyter Notebook 在 VSCode 中编码 MATLAB 不会因错误而停止执行
- python - 使用随机值对创建列表
- angular - Angular 和与 Entity Framewok Core 的多对多关系
- angular - 如何使用 rxjs 简化发射变化?
- python - undetected_chromedriver.v2 代理不工作 (proxy_auth_plugin.zip)
- html - 如何启用文件夹上传到
我正在做一个小项目,我的访问者可以上传他们的文件、图像等,一旦他们点击“发送”按钮,它就会将他们上传的内容发送到我设置的电子邮件地址。现在这里的问题是,如果访问者上传例如 5 个文件,它只会随机发送这 5 个文件中的一个,我希望它发送所有文件,那么有没有办法实现这一点?
我想我可以通过使文件上传字段接受文件夹来做到这一点,但我不确定如何准确地做到这一点,我知道我可以将文件夹
- excel - 将输入框变量从一个子传递到另一个
- jquery - 带有 webpack 的 daterangepicker 失败
- reactjs - 如何测试 Stripe 与 React 测试库的集成。无法渲染卡片元素