简体   繁体   中英

React refresh component when variable has changed

I am calling a React component BarChart with two props, a name and a value . As you can see in the below code, the variable value is set to a new random number every second:

    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>
  )
}

Inside the React component I call it by using this.props.value1 . When I do a console.log(this.props.value1) each second inside the React component, I get an error that the variable is undefined after the first print is made. So, it prints to the console 1 time and then it just prints an error for all of the rest attempts.

This is how I print the variable inside the component:

setRandom() {
    console.log(this.props.value1)
}

componentDidMount() {
    this.setRandom();
    setInterval(this.setRandom, 1000);
}

What I really want to do is that whenever a new random value is generated outside the component, the component should see that the variable has changed and refresh the component and use the new prop.

Could you please advise me?

The standard way to do this is to make random1 a piece of state information , and then use this.setState to update it.

The first link above has an example of a ticking clock, which is virtually identical to your example of a random number every second. Here's that example, which you can readily adapt to your task:

 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>
)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM