我想知道为什么为什么时间每秒钟更新一次,而运行代码时却只一次更新一次?我知道这可能与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>
);
}
}
谢谢!
答案 0 :(得分:3)
每秒钟将tick变量设置为新的Date时,问候语状态变量始终设置为Hola
。因此,在第一次调用tick
的1秒时,greetings
从Bonjour
更改为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"/>