我有一个React组件,它显示一个实体的信息。实体的id是通过属性传入的。该组件在"componentDidMount“中启动AJAX调用以获取实体,并在调用完成/失败时更新状态。
除了组件不会在实体id更改时获取新数据(通过props)之外,这种方法工作得很好。
我尝试过在"componentWillReceiveProps“中启动一个调用,但在那个阶段,组件仍然设置了旧的属性。我必须将nextProps传递给AJAX调用方法,但这似乎并不正确。
让组件异步更新其状态以响应属性更改的最好/最干净的方式是什么?
发布于 2015-12-01 21:26:06
我也是个新手,所以Flux架构对我来说有点吓人。我完全按照你说的做,使用componentWillMount
通过AJAX加载初始数据,然后使用nextProps
的componentWillReceiveProps
在属性发生变化时再次加载新数据:
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>
);
}
});
https://stackoverflow.com/questions/30704585
复制相似问题