什么时候ReactJS组件应该使AJAX调用从props更新状态?

Dav*_*ker 18 javascript ajax reactjs

我有一个React组件,显示有关实体的信息.实体的id通过属性传入.该组件在"componentDidMount"中启动AJAX调用以获取实体并在调用完成/失败时更新状态.

这种方法很好,只是当实体id更改时(通过props)组件不会获取新数据.

我已尝试在"componentWillReceiveProps"中启动调用,但在该阶段,组件仍具有旧属性集.我必须将nextProps传递给AJAX调用方法,这似乎不对.

使组件异步更新其状态以响应属性更改的最佳/最干净方法是什么?

wnm*_*wnm 9

我也是新的反应,所以Flux架构对我来说有点吓人.我正是这样做如你所说,使用componentWillMount通过AJAX来加载初始数据,然后componentWillReceivePropsnextProps如果/当道具再次改变加载新的数据:

var Table = React.createClass({
  getInitialState: function() {
    return { data: [] };
  },

  componentWillMount: function(){
    this.dataSource();
  },

  componentWillReceiveProps: function(nextProps){
    this.dataSource(nextProps);
  },

  dataSource: function(props){
    props = props || this.props;

    return $.ajax({
      type: "get",
      dataType: 'json',
      url: '/products?page=' + props.page + "&pageSize=" + props.pageSize
    }).done(function(result){
      this.setState({ data: result });
    }.bind(this));
  },

  render: function() {
    return (
      <table className="table table-striped table-bordered">
        <Head />
        <Body data={this.state.data}/>
      </table>
    );
  }
});
Run Code Online (Sandbox Code Playgroud)