gpt4 book ai didi

javascript - ReactJS setState方法: Time updates per second but 'greeting' won't?

转载 作者:行者123 更新时间:2023-11-28 17:28:11 25 4
gpt4 key购买 nike

我想知道为什么时间每秒更新一次,但当我运行代码时问候语只更新一次?我知道这可能与 React 仅更新必要的内容有关。以下是代码:

class App extends React.Component {

constructor(props) {
super(props);
this.state = { date: new Date(), greeting: "Bonjour" };
}

componentDidMount() {
this.timerID = setInterval(this.tick, 1000);
}

componentWillUnmount() {
clearInterval(timerID);
}

tick = () => { this.setState({ date: new Date(), greeting: "Hola" }); }

render() {
return (
<div>
<h1>{this.state.greeting} {this.props.name}!</h1>
<h2>It is {this.state.date.toLocaleTimeString()} right now!</h2>
</div>
);
}

}

谢谢!

最佳答案

虽然刻度变量每秒都会设置为新的日期,但问候语状态变量每次都会设置为 Hola。因此,在第一次调用 tick 时的 1 秒,greetingsBonjour 更改为 Hola 以及随后的每次调用,因为它设置为 Hola,它以相同的值重新渲染

因此,在您的情况下,问候语仅更新一次。如果您希望它也发生变化,您可以定义一组可能的值并以循环或随机方式显示它们

const greet = ["Hola", "Hey", "Bonjour", "Hi" ];
class App extends React.Component {

constructor(props) {
super(props);
this.state = { date: new Date(), greeting: "Bonjour" };
}

componentDidMount() {
this.timerID = setInterval(this.tick, 1000);
}

componentWillUnmount() {
clearInterval(timerID);
}

tick = () => {
const ridx = Math.floor(Math.random(greet.length)*(greet.length));
this.setState({ date: new Date(), greeting: greet[ridx] });
}

render() {
return (
<div>
<h1>{this.state.greeting} {this.props.name}!</h1>
<h2>It is {this.state.date.toLocaleTimeString()} right now!</h2>
</div>
);
}

}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"/>

关于javascript - ReactJS setState方法: Time updates per second but 'greeting' won't?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51059208/

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