猿问

当变量改变时反应刷新组件

我正在调用一个BarChart带有两个道具 aname和 a的 React 组件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. 当我console.log(this.props.value1)在 React 组件中每秒执行一次操作时,出现第一次打印后变量未定义的错误。因此,它会打印到控制台 1 次,然后它只会为所有其余的尝试打印一个错误。


这就是我在组件内打印变量的方式:


setRandom() {

    console.log(this.props.value1)

}


componentDidMount() {

    this.setRandom();

    setInterval(this.setRandom, 1000);

}

我真正想做的是,每当在组件外部生成新的随机值时,组件应该看到变量已更改并刷新组件并使用新的 prop。


你能给我建议吗?


jeck猫
浏览 204回答 2
2回答

慕斯709654

执行此操作的标准方法是制作random1一条状态信息,然后使用this.setState它来更新它。上面的第一个链接有一个滴答时钟的例子,它几乎与你每秒随机数的例子相同。这是您可以轻松适应您的任务的示例:class Clock extends React.Component {&nbsp; constructor(props) {&nbsp; &nbsp; super(props);&nbsp; &nbsp; this.state = {date: new Date()};&nbsp; }&nbsp; componentDidMount() {&nbsp; &nbsp; this.timerID = setInterval(&nbsp; &nbsp; &nbsp; () => this.tick(),&nbsp; &nbsp; &nbsp; 1000&nbsp; &nbsp; );&nbsp; }&nbsp; componentWillUnmount() {&nbsp; &nbsp; clearInterval(this.timerID);&nbsp; }&nbsp; tick() {&nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; date: new Date()&nbsp; &nbsp; });&nbsp; }&nbsp; render() {&nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <h1>Hello, world!</h1>&nbsp; &nbsp; &nbsp; &nbsp; <h2>It is {this.state.date.toLocaleTimeString()}.</h2>&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; );&nbsp; }}ReactDOM.render(&nbsp; <Clock />,&nbsp; document.getElementById('root'));

LEATH

constructor(props) {&nbsp; super(props);//innitialize the random number in the state&nbsp; this.state = {random: Math.floor(Math.random() * 10) + 1};}//generate the random number and keep in on the state&nbsp; setRandom() {&nbsp; &nbsp; this.setState({random: Math.floor(Math.random() * 10) + 1})&nbsp; }//clear the timer when component unmountcomponentWillUnmount() {&nbsp; clearInterval(this.timer);}componentDidMount() {//start the timer when component mount&nbsp; this.timer = setInterval(()=>this.setRandom(), 1000);}//pass the random value from state as props to the component BarChart&nbsp; return (&nbsp; <div className="Content">&nbsp; &nbsp; &nbsp; <BarChart name1={"A"} value1={this.state.random}/>&nbsp; </div>)}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答