Redux - 智能组件 - 如何在安装组件之前处理异步操作?

时间:2016-02-11 15:30:59

标签: javascript reactjs redux redux-thunk

我正在构建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

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

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

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

谢谢!

1 个答案:

答案 0 :(得分:0)

您可以简单地使用条件。

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”属性并在呈现真实时呈现微调器或其他内容。

相关问题