在传入的道具更改后,如何强制组件重新渲染?
前提:在我的基本页面上,有一个进度栏。用户可以从该基本页面访问许多模式页面。进度条应可视化用户已查看了多少个模态。
原则上,大多数方法都有效。唯一的问题是,当传入的progress
道具更改时,进度条组件不会重新渲染视觉进度条。
<ProgressBar
progress={ this.props.progress }
/>
进度栏组件本身知道更改,并会很高兴地重新呈现一个文本字段,该文本字段打印progress
的值以反映更新后的值。但是,它不会以反映更改后的道具的方式重新渲染视觉进度条(带有样式的一系列视图组件)。文本字段更改,视图不更改。
这是我的代码。难道我还需要在某种更新功能中重复在ComponentDidMount()
中所做的计算吗?
// Progress Bar component
export default class ProgressBar extends React.Component {
state = {
// define some variables
}
componentDidMount() {
// do some math using this.props.progress and state
// to calculate the percentage etc that the views use to
// display the length of the progress bar
}
componentWillUpdate( prevProps, prevState ) {
// I tried repeating the above calculations in here as well
// but anything I place in here will result in error message:
// Invariant Violation: Maximum update depth exceeded...
}
render() {
// a number of views that create a visual progress bar
// entirely dependent on calculated values, i.e. not directly
// referencing this.props.progress
}
}
任何指导将不胜感激!
答案 0 :(得分:1)
当传递的道具更改时,getDerivedStateFromProps()
在渲染方法之前被调用。在这里,您可以将当前状态与新数据进行比较,并返回一个对象或null以不进行任何更新。
static getDerivedStateFromProps(props, state)
答案 1 :(得分:0)
但是,它不会以反映更改后的道具的方式重新渲染视觉进度条(带有样式的一系列视图组件)。文本字段更改,视图不更改。
这证明此组件的翻译很好。无需搜索魔术子弹,这是强制释放的另一种方式。 组件会根据道具变更重新提供。
render() {
// a number of views that create a visual progress bar
// entirely dependent on calculated values, i.e. not directly
// referencing this.props.progress
}
我们需要更多的数据/代码-这是问题的根源。子组件的构造可能导致“停止重新渲染过程向下传播”。 如果直接孩子中的任何一个不进行降级,而较深层的孩子则不进行降级。
答案 2 :(得分:-2)
仅当状态已更改时才能触发重新渲染。状态可以从props更改或直接setState更改更改。组件获取更新后的状态,React决定是否应重新渲染组件。
因此组件将传递状态,如果状态将改变其对渲染的影响 类Progress扩展了React.Component {
componentDidMount() {
setInterval(() => {
this.setState(() => {
progress:true
});
}, 1000);
}
render() {
return (<div>{this.state.progress ? <div> true </div>: <div>false</div>}</div>);
}
}