我对 React 世界有点陌生,最近当我开始在组件中编写 Ajax 内容时感到困惑。
据我所知,这里有两种将异步数据渲染到组件中的方法,如下所示:
第一种方式:
class MyComponent extends React.Component
{
render() {
this.props.userList.map((userInfo) => (<span>{userInfo.name}</span>));
// proceed to render userList
}
}
//userAjaxSelect is a customized selector based on the Reselect lib
//ajax operation happens here!!
const mapStateToProps = (state, props) => {
return {
userList:userAjaxSelect(state, props)
}
}
const mapDispatchToProps = null;// mapDispatchToProps is omitted here
export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)
方式二:
export default class MyComponent extends React.Component
{
componentDidMount() {
//FetchUserList is a redux ActionCreator and omitted here
//it dispatches redux action
//To get ajax response and sync to local UI state.
this.setState({userList: FetchUserList(this.props.groupId)})
}
componentWillReceiveProps(nextProps) {
if(nextProps != this.props)
//FetchUserList is a redux ActionCreator and omitted here
//it dispatches redux action
//To get ajax response and sync to local UI state.
this.setState({userList: FetchUserList(nextProps.groupId)})
}
render() {
this.state.userList.map((userInfo) => (<span>{userInfo.name}</span>);
// proceed to render userList
}
}
从我的观点,
第一个解决方案:
ajax 操作封装在 Reselect 库中使用的 Selector 中,我认为它非常干净并且可以使组件性能受益(通过缓存)
第二种解决方案:
它是坏的吗?因为很多时候我被几篇文章警告过,不鼓励 componentWillReceiveProps 设置状态(反模式)?而且它的实现方式比较冗长
哪一个是最佳实践或任何其他更好的选择?加载和刷新 Ajax 数据时