【问题标题】:Redux - smart components - how do you handle asynchronous action before mounting a component?Redux - 智能组件 - 在安装组件之前如何处理异步操作?
【发布时间】:2016-05-22 11:20:54
【问题描述】:

我正在构建一个 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的时候,属性user不一定存在。

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

您如何处理初始组件状态? 你是否依赖componentWillReceiveProps 来刷新你的用户界面? 您使用的是isFetching 属性吗?

谢谢!

【问题讨论】:

    标签: javascript reactjs redux redux-thunk


    【解决方案1】:

    您可以简单地使用条件。

    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 时渲染一个微调器或其他东西。

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-04-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      • 2021-04-03
      • 2017-08-29
      相关资源
      最近更新 更多