[英]React refresh component when variable has changed
我正在調用一個帶有兩個道具的 React 組件BarChart
,一個name
和一個value
。 正如您在下面的代碼中看到的,變量值每秒設置為一個新的隨機數:
let random1;
function setRandom() {
random1 = Math.floor(Math.random() * 10) + 1;
}
setRandom();
setInterval(setRandom, 1000);
return (
<div className="Content">
<BarChart name1={"A"} value1={random1}/>
</div>
)
}
在 React 組件中,我使用this.props.value1
來調用它。 當我在 React 組件內每秒執行一次console.log(this.props.value1)
時,我收到一個錯誤,即在第一次打印后變量未定義。 因此,它打印到控制台 1 次,然后它只是為所有 rest 嘗試打印一個錯誤。
這就是我在組件內打印變量的方式:
setRandom() {
console.log(this.props.value1)
}
componentDidMount() {
this.setRandom();
setInterval(this.setRandom, 1000);
}
我真正想做的是,每當在組件外部生成新的隨機值時,組件應該看到變量已更改並刷新組件並使用新的道具。
你能告訴我嗎?
執行此操作的標准方法是使random1
成為一條state 信息,然后使用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') );
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>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.