Redux - 智能组件 - 在挂载组件之前如何处理异步操作



我正在构建一个React/Redux应用程序,查询API以获取有关用户的数据。

我正在尝试在这里重用本教程:https://rackt.org/redux/docs/advanced/ExampleRedditAPI.html

假设我有一个容器组件UserPage,它显示给定用户的信息:

class UserPage extends Component {
  componentWillMount() {
    this.props.dispatch(fetchUser(this.props.user.id));
  }
  render() {
    <UserProfile name={this.props.user.name} />
  }
}
const mapStateToProps = (state, ownProps) => {
  return {
    user: _.find(state.users, (user) => user.id == ownProps.params.userId)),
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
    dispatch
  };
};
export default connect(mapStateToProps, mapDispatchToProps)(UserPage);

为了获取当前用户,我进行了一次 API 调用: GET /api/users/:userId

我的问题是在初始化组件时,属性用户不一定存在。

因此,弹出错误can't call property name on undefined

如何处理初始组件状态?您是否依靠componentWillReceiveProps来刷新您的 UI?您使用的是isFetching属性吗?

谢谢!

您可以简单地使用条件。

class UserPage extends Component {
    componentWillMount() {
        this.props.dispatch(fetchUser(this.props.user.id));
    }
    renderUser() {
        if (this.props.user) {
            return (
                <UserProfile name={this.props.user.name} />
            )
        }
    }
    render() {
        return (
            <div>{this.renderUser()}</div>
        )
    }
}

正如您所提到的,您可能希望有一个"isFetching"属性,并在 true 时呈现微调器或其他内容。

最新更新