[英]re-rendering React Component
I have a react class in which I need to use shouldComponentUpdate()
, to prevent an infinite loop between the component and its parent. 我有一个react类,需要在其中使用
shouldComponentUpdate()
,以防止组件与其父对象之间发生无限循环。
I simply check whether a deep clone of nextProps
is equal to this.props
, and I only update the component if they're not. 我只是简单地检查
nextProps
的深层克隆是否等于this.props
,并且仅更新不相等的组件。
So far, so good. 到现在为止还挺好。 (?)
(?)
class Child extends Component {
onComponentUpdate = (e) => {
this.props.update(e)
}
shouldComponentUpdate(nextProps, nextState) {
return JSON.stringify(nextProps) !== JSON.stringify(this.props)
}
render() {
return (
<div>
// some code that might trigger onComponentUpdate()
</div>
);
}
}
Now, in my parent component, something happens that makes me want to re-render the child, without specific props changing. 现在,在我的父组件中,发生了一些事情,使我想在不更改特定道具的情况下重新渲染孩子。 What I did now, is changing a counter in state and passing it to the child as a prop.
我现在要做的是更改状态计数器,并将其作为道具传递给孩子。 I never do anything with the counter itself, it is merely an indication for the child that props actually changed so that the child should update.
我从不对计数器进行任何操作,这只是指示孩子道具实际发生了变化,以便孩子可以更新。
class Parent extends Component {
constructor() {
super()
this.state = { counter: 0 }
}
otherChildChanged = () => {
this.setState({ counter: this.state.counter + 1 })
}
render() {
return (
<div>
<Child
counter={this.state.counter}
update={"some function"}
other={"props"}
>
</Child>
<OtherChild onChange={this.otherChildChanged}>
</OtherChild>
// some code that might trigger onComponentUpdate()
</div>
);
}
}
Is there a better way to do this? 有一个更好的方法吗?
You should pass down the size of your resizable div as a prop to the Child Component. 您应该向下传递可调整大小的div的大小,以作为子组件的支持。 This way, when it changes,
JSON.stringify(nextProps) !== JSON.stringify(this.props)
will be true
and a re-render will occur. 这样,当它更改时,
JSON.stringify(nextProps) !== JSON.stringify(this.props)
将为true
并且将进行重新渲染。
If a component has to behave in a certain way (re-render, for example) depending on something that happens on his Parent, it should be passed to it as a prop. 如果某个组件必须根据其父上发生的某些事情以某种方式(例如重新渲染)运行,则应将其作为道具传递给它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.