2017-06-29 105 views
2

我喜欢通过每分钟创建一次新的API调用来创建一个保持最新的视图。基本上需要触发所有子组件重新渲染,并再次进行API调用。我试着用forceUpdate(),以及更新道具(下面)。计时器是工作,但子组件未呼吁更多数据强制子元素重新渲染(创建API调用)

目前的组件看起来像这样的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); 
    } 
... 

我希望在这里,那当prop查询参数随着nuw时间戳(它所做的)改变时,Api组件将重新渲染并调用“新”端点。道具确实会改变,但API不会再被调用,为什么?

回答

1

使用不同的lifecycle method。 componentDidMount仅在组件第一次添加到dom时调用,而不是在随后的重新呈现期间调用。 shouldComponentUpdate可能是你想要的。

+0

哪个生命周期适合这个? –

+0

刚刚编辑。 shouldComponentUpdate可能是你想要的,但componentWillReceiveProps也可以。只是不是componentDidMount,因为它只被调用一次。 – gvfordo

+0

你能详细说一下,还是提供一个例子?将'_makeApiCall'移动到'shouldComponentUpdate'中似乎没有问题 –