[英]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.