强制子组件重新发布(进行API调用)

时间:2017-06-29 18:15:57

标签: reactjs

我想通过每分钟拨打新的API来创建一个保持最新状态的视图。基本上需要触发所有子组件重新渲染,并再次进行API调用。我尝试过使用forceUpdate(),以及更新prop(下面)。计时器正在运行,但子组件未调用API以获取更多数据

目前该组件如下所示:

class MyComponent extends React.Component<Props, State> {

  state = {
    time: 0
  };

  private interval : any;

  componentDidMount() {
    this.interval = setInterval(this._refreshPage.bind(this), 1000);
  }
  componentWillUnmount() {
    clearInterval(this.interval);
  }

  _refreshPage() {
    console.log("refresh");
    //this.forceUpdate();
    this.setState({ time: Date.now() });
  }

  render () {
    return (
      <div className="MyComponent">

          <Api endpoint={'/api/revenue/total_revenue?' + this.state.time} loadData={true}>
            <Table />
          </Api>
...

API:

class Api extends React.Component {

  componentDidMount() {
    this._makeApiCall(this.props.endpoint);
  }
...

我希望在这里,当支持查询参数随着nuw时间戳(它确实)而改变时,Api组件将重新渲染并调用&#34; new&#34;端点。道具确实发生了变化,但是API没有被再次调用,为什么?

1 个答案:

答案 0 :(得分:1)

使用其他lifecycle method。 componentDidMount仅在组件第一次添加到dom时调用,而不是在任何后续重新渲染期间调用。 shouldComponentUpdate可能就是你想要的那个。