重新渲染后,我的一个组件没有得到更新。它只是偶尔发生。
我检查了组件是否正确呈现。在下面的代码中,您将在 render
函数中看到一个 console.log
。我意识到值(value)改变正确。但是组件本身不会在视觉上更新。我认为我不会改变任何状态/ Prop 。我用 Redux对于大多数状态管理。你知道为什么会这样吗?谢谢。
子组件如下所示:
export default ChildComponent extends React.Component {
...
render() {
...
const barWidth = this.getProgressWidth(boundingClientRect) // also uses this.props.editorTimestamp
console.log(barWidth) // This value is updated like I expect
return (
<div>
...
<div style={{...styles.barStyles, width: barWidth }}>
...
</div>
)
}
}
父组件如下所示:
export default ParentComponent extends React.Component {
...
render() {
...
const singleEditorTimestamp = this.getEditorTimestamp(id) // gets the timestamp from timestamps obj
return (
<div>
...
<ChildComponent editorTimestamp={singleEditorTimestamp} />
...
</div>
)
}
}
最佳答案
state
或 props
更改可以触发渲染。还有 this.forceUpdate();
你可以这样做
const barWidth = this.getProgressWidth(boundingClientRect)
this.setState({barWidth: barWidth});
但是在 render 中改变状态并不是一个好主意。因为它会触发无限渲染过程。您应该声明一个 event
并在该事件中更改 state
。 :)
关于reactjs - React - 组件在重新渲染后不更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58032899/