【问题标题】:React/Flux seState not re-rendering component after API callAPI 调用后 React/Flux seState 不重新渲染组件
【发布时间】:2017-10-05 16:57:02
【问题描述】:

我正在调用一个 API,它允许您按不同的参数对它返回的数据进行排序,例如顶部、最新、流行等。我想要实现的是,当用户单击按钮以按不同参数排序时,状态将更改为新参数,并使用该新参数再次调用 API。这是我的代码:

constructor (){
    super();
    this.state = {
        sortType: 'top' //default is to sort by Top
    };

    this.setSortType = this.setSortType.bind(this);
}
componentWillMount(){
    //this retrieves sourceName which is required to make the API call
    const parsed = queryString.parse(this.props.location.search);
    var sourceName = parsed.sourceId;

    //getArticles below is the action that makes the API call with sourcename and sortType as parameters  

    newsActions.getArticles(sourceName,this.state.sortType);
    newsStore.on('articles_change',this.fetchNewsArticles);

}
//Call to setState when user clicks button change sort parameter
setSortType(){
    this.setState({
        sortType:'latest'
    });
}

render() {
    return (
        <div>
        ... //logic to display data from the API call 
        <button onClick={this.setSortType}> Sort By Latest </button>
        </div>
    );
}

单击按钮时,不会重新呈现任何内容。我错过了什么?

【问题讨论】:

    标签: javascript reactjs flux reactjs-flux


    【解决方案1】:

    React 在组件挂载时只调用一次componentWillMount,因此它包含的逻辑不会在状态更改时再次执行更新。

    查看React docs,以更好地了解 React licecycle hooks 的工作原理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-06
      • 2016-08-17
      • 2021-07-06
      • 1970-01-01
      • 2019-02-20
      • 1970-01-01
      • 2019-12-23
      • 2021-04-28
      相关资源
      最近更新 更多