gpt4 book ai didi

javascript - 在ReactJS中修改状态对象直接重新渲染组件

转载 作者:行者123 更新时间:2023-12-01 01:30:07 33 4
gpt4 key购买 nike

我正在浏览 ReactJS 文档。我在状态和生命周期部分遇到了以下概念:

Do Not Modify State Directly For example, this will not re-render a component:

// Wrong
this.state.comment = 'Hello';

https://reactjs.org/docs/state-and-lifecycle.html

我尝试实现相同的行为,发现组件被重新渲染

class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {
time : new Date(),
note: "Time is-"
}
}
componentDidMount() {
this.timerId = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearTimer(this.timerId);
}
render() {
return <h1>{this.state.note}{this.state.time.toLocaleTimeString()}</h1>
}
tick() {
this.state.note = "Dude!! Time is";
this.setState({
time : new Date()
})
}
}

ReactDOM.render(
<Clock/>,
document.getElementById('root')
);

文本从“Time is”重新渲染为“Dude Time is”

有人能解释一下吗?这种行为违背了 react 文档所说的

最佳答案

这是有效的,因为您还在 this.state.note = "Dude!! Time is" 之后执行 setState。如果您删除此行之后的 setState 调用,则该示例将不起作用。

这里是codesandbox 的链接。我删除了 setState 调用。

https://codesandbox.io/s/50r500j62p

关于javascript - 在ReactJS中修改状态对象直接重新渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53358361/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com