为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

jeck猫 2021-11-04 15:11:30
我正在调用一个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。你能给我建议吗?
查看完整描述

2 回答

?
慕斯709654

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

);


查看完整回答
反对 回复 2021-11-04
?
LEATH

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>

)

}


查看完整回答
反对 回复 2021-11-04
  • 2 回答
  • 0 关注
  • 203 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信