2 回答
![?](http://img1.sycdn.imooc.com/545862120001766302200220-100-100.jpg)
TA贡献1840条经验 获得超5个赞
执行此操作的标准方法是制作random1一条状态信息,然后使用this.setState它来更新它。
上面的第一个链接有一个滴答时钟的例子,它几乎与你每秒随机数的例子相同。这是您可以轻松适应您的任务的示例:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('root')
);
![?](http://img1.sycdn.imooc.com/545845e900013e3e02200220-100-100.jpg)
TA贡献1936条经验 获得超6个赞
constructor(props) {
super(props);
//innitialize the random number in the state
this.state = {random: Math.floor(Math.random() * 10) + 1};
}
//generate the random number and keep in on the state
setRandom() {
this.setState({random: Math.floor(Math.random() * 10) + 1})
}
//clear the timer when component unmount
componentWillUnmount() {
clearInterval(this.timer);
}
componentDidMount() {
//start the timer when component mount
this.timer = setInterval(()=>this.setRandom(), 1000);
}
//pass the random value from state as props to the component BarChart
return (
<div className="Content">
<BarChart name1={"A"} value1={this.state.random}/>
</div>
)
}
添加回答
举报