【问题标题】:How to load object from route parameter using redux如何使用 redux 从路由参数加载对象
【发布时间】:2016-11-20 01:41:27
【问题描述】:

我正在使用 react-router-redux,我有这样的路由

<Route path="/user/:userId" components={{ body: UserMaintenance }} />

在路由中加载userId参数对应的用户对象的推荐方式是什么?

我的想法(我是 react 和 redux 的新手)是在 UserMaintenance componentWillReceiveProps 方法中使用 userId 参数并将 FETCH_USER 操作发送到将加载到 state.currentUser 的商店。当 currentUser 参数因操作而更新时,UserMaintenance 组件将随之更新。

【问题讨论】:

标签: reactjs redux react-router-redux


【解决方案1】:

我建议您将该逻辑移至 Container Component,将 connects UserMainenance 移至您的 redux store

这将帮助您将数据层与Presentational Component 分开,后者不应该知道如何获取要渲染的数据。它只需要知道如何呈现该数据。

import React, {Component, PropTypes} from 'react';
import {connect} from 'react-redux';
import {fetchUser} from './actions';
import UserMaintenance from './UserMaintenance';

class UserContainer extends Component {
  componentWillMount() {
    const {fetchUser, userId} = this.props;
    fetchUser(userId);
  }

  render() {
    return (
      <UserMaintenance {...this.props} />
    );
  }
}

const mapStateToProps = (state, ownProps) => ({
  userId: ownProps.params.userId
  user: state.user,

});

export default connect(
  mapStateToProps, {fetchUser}
)(UserContainer);

假设你有fetchUser actionCreator。

我强烈建议您在https://egghead.io 上观看 Dan Abramov(Redux 的创建者)的Browse the Building React Applications with Idiomatic Redux course。它是免费的,并且很好地涵盖了这个主题。

【讨论】:

  • 谢谢。我确实将这些视为学习这一切的第一步,但现在我实际上已经在使用它,因此值得很快回顾一下。
【解决方案2】:

首先,您必须决定是否希望您的 URL 成为 userId 的真实来源(我建议这样做)。

那么你就知道,只要 URL/路由发生变化,你就会派发FETCH_USER

要从应用程序中的其他位置更改用户,您只需 browserHistory.push('/user/1234') 并知道 URL 的更改将触发对商店的更新。

如果您对此感到满意,只需在路由中调度操作:

<Route
  path="/user/:userId"
  components={{ body: UserMaintenance }}
  onEnter={state => {
    store.dispatch({
      type: ACTIONS.FETCH_USER,
      key: state.params.userId,
    });
  }}
/>

如果你遵循这个逻辑,你可能不需要react-router-redux

来自redux作者over here的有趣的cmets。

【讨论】:

  • 谢谢,很简单。该链接中确实有趣的 cmets。
猜你喜欢
  • 2020-08-24
  • 2020-12-16
  • 2020-02-15
  • 1970-01-01
  • 1970-01-01
  • 2023-04-01
  • 1970-01-01
  • 2017-06-30
  • 2020-09-05
相关资源
最近更新 更多