react 的官方文档(https://reactjs.org/docs/react-component.html)说 props 的更新会导致孩子被更新,但在我的代码中并没有发生。我错过了什么吗?
我创建了一个父组件 (Y) 和一个子组件 (X)。父母将 currentTime 作为道具传递给孩子。即使在 3 秒后父项中的 props 发生变化(由于 setTimeout),子项中 h2 标记中的值也不会改变。
我在 react 的官方页面(https://reactjs.org/docs/react-component.html)上发现“更新可能是由 props 或 state 的更改引起的。” (我在下面的官方网站上附上了屏幕截图以及文本)此外,我发现“这些方法在重新渲染组件时被调用:”
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
但在我的情况下,道具的变化不会导致孩子中 h2 标签中的值发生变化。官方文档说 props 的更新会导致 child 被更新,但在我的代码中并没有发生。我错过了什么吗?
我在这里粘贴了我的代码以供参考。
const Y = () => {
let currentTime="09:00";
setTimeout(()=> {
currentTime = "10:00:"
}, 3000);
return (
<X time={currentTime}/>
);
};
class X extends Component {
time = "11:00";
render = () => {
return (
<h2>{this.props.time}</h2>
);
};
}
更新:Shubham Khatri 的评论“只有当父母重新渲染时,孩子的道具才会改变”,真的帮助我理解了。:)