javascript - 事件渲染前如何获取道具
问题描述
我是 React 的初学者,在渲染孩子之前从父母那里获取道具有问题。
如您所见,我有一个编辑器组件,它将字符串作为道具发送到按钮。在有人单击按钮(onClick 事件)之前收集的位置,然后使用道具(来自编辑器)更新状态并作为道具发送到 DataTable,其中方法componentWillReceiveProps将道具作为获取请求发送。
!但是当我点击按钮时!在 DataTable 组件从按钮接收道具之前调用 fetch。我知道孩子在父母之前被称为现在该怎么办?我迷失在其中。
这是一些代码
按钮
componentWillReceiveProps(nextProps, nextContext) {
if(nextProps.queryFromEditor !== this.props.queryFromEditor){
this.setState({queryFromEditorString: nextProps.queryFromEditor.join(' ')});
}
}
submitData= () =>{
this.setState({
buttonState: !this.state.buttonState,
queryFromEditorString: this.state.queryFromEditorString,
});
//console.log('Button: '+ this.state.queryFromEditorString)
}
render(){
return(
<div>
<div className="submit">
<input onClick={this.submitData} id="querySend"
type="submit"
value="Submit query"
/>
</div>
<DataTable
queryFromEditorString = {this.state.queryFromEditorString}
buttonState = {this.state.buttonState}/>
</div>
)
}
数据表
componentWillReceiveProps(nextProps, nextContext) {
if(nextProps.buttonState !== this.props.buttonState){
this.setState({queryFromEditor: nextProps.queryFromEditorString});
console.log('Component: '+this.state.queryFromEditor)
this.fetchQuery()
}
}
fetchQuery(){
fetch('/api/query',
{
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ content: this.state.queryFromEditor})
})
.then(res => res.json())
.then(qo =>{ this.setState({queryOutput: qo})
console.log('Table fetch: '+JSON.stringify(qo))
})
}
componentDidMount(){
//Fetching number of affected and changed rows
fetch('/api/update')
.then(res => res.json())
.then(rows => {this.setState({rows: rows})
console.log(rows)
});
//Fetching output from user query
this.fetchQuery()
}
render(){...}
解决方案
this.setState是异步的,这意味着它不会立即更新组件。
如果您真的想从道具更新状态,我建议您改用getDerivedStateFromProps。另一种解决方案是在 setState 的回调中调用 this.fetchQuery() 以确保更新完成,如下所示:
this.setState({queryFromEditor: nextProps.queryFromEditorString}, () => {
console.log('Component: '+this.state.queryFromEditor)
this.fetchQuery()
});
但是,为什么不直接使用fetchQuery中的道具,而不是将其设置为 state 呢?
body: JSON.stringify({ content: this.props.queryFromEditor})
推荐阅读
- javascript - 如何将表单数据发送到服务器
- python - 如何使用 keras 在输入特征子集之间共享权重
- c# - 渲染纹理会减慢统一速度?
- python - Python Selenium:加载 Firefox 配置文件时没有这样的文件或目录
- javascript - 在运行时延迟加载和导入未编译的 JS(X) 文件
- ruby-on-rails - 带有carrierwave Dropbox存储和rails的heroku始终显示相同的图像
- java - java swagger 示例字符串帖子正文
- python - 如何以所需的方式打印输出?
- reactjs - 在 React 应用程序中运行 npm start 时出现 babel-jest 依赖问题
- python-2.7 - pyqt marquee 文本在几个小时后挂起