reactjs - 如何解决“加载后发送操作,循环问题”
问题描述
我正在尝试从我的仪表板页面发送数据操作this.props.dataActions.addChild(this.props.user.children.data[0])
。
但我有一个循环问题。我不知道在这种情况下该怎么办。请在下面检查我的代码:
我试图添加加载,componentDidUpdate
但没有帮助。
componentDidUpdate() {
//
console.log(this.state.loading)
if (this.props.user && this.props.user.children && this.props.user.children.data) {
console.log('iiiii', this.props.user.children.data[0])
this.props.dataActions.addChild(this.props.user.children.data[0])
if (!this.state.loading) {
this.setState({ selectedChildren: this.props.user.children.data[0] })
}
}
}
请检查截图:
停止循环并this.props.dataActions.addChild
仅发送一次的最佳方法是什么
仪表板索引代码: https ://pastebin.com/5V2ceAHK
解决方案
不建议setState
在 didUpdate 生命周期内使用。但是,如果您对生命周期方法别无选择,则必须非常小心设置状态的条件
componentDidUpdate() {
//
console.log(this.state.loading)
if (this.props.user && this.props.user.children && this.props.user.children.data) {
console.log('iiiii', this.props.user.children.data[0])
this.props.dataActions.addChild(this.props.user.children.data[0])
if (
!this.state.loading &&
this.state.selectedChildren !== this.props.user.children.data[0] // see this line here ??
) {
this.setState({ selectedChildren: this.props.user.children.data[0] })
}
}
}
在上面的代码中,您应该检查 selectedChildren 是否还不是您所在州的内容
this.state.selectedChildren !== this.props.user.children.data[0]
如果这selectedChildren
是一个对象,您必须使用对象比较模块,无论是定制的还是来自供应商包的。有关对象相等性的更多信息,请参阅此
编辑:在您的代码中
componentDidUpdate(prevProps) {
//
if (
this.props.user &&
this.props.user.children &&
this.props.user.children.data &&
checkIf_prevProps.child isNotEqualTo this.props.user.children.data[0]
) {
console.log('iiiii', this.props.user.children.data[0])
this.props.dataActions.addChild(this.props.user.children.data[0])
}
}
所以检查是否checkIf_prevProps.child isNotEqualTo this.props.user.children.data[0]
. 或者简单地检查状态变量中的任何条目,这样您就知道状态已经更新了。但请记住,这是一种保护无限渲染的肮脏黑客行为。
推荐阅读
- java - fetchInto 时 JOOQ 记录中的字段未排列
- python - 创建依赖于属性文件的子模块
- python-3.x - Python-如果变量的条件为真,则执行分配新变量的函数,直到为假
- php - 根据需要自动构建尽可能多的嵌套循环?
- rabbitmq - RabbitMQ 和物联网设备:保持队列开放?
- python - 为围绕一个随机圆圈的圆圈分配特定颜色
- python - Pandas:检查 json 对象中是否存在数据框列
- nativescript - NativeScript:带有文本叠加的图像 | GridLayout 不适合内容
- angular - 单击上一个 - Angular 6时,mat-stepper 重置前进步骤
- nativescript - 扩展 TnsOaProviderType