2

我正在使用 react-router-redux 并且我有这样的路线

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

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

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

4

2 回答 2

4

首先,您必须决定是否希望您的 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 的作者在这里发表了有趣的评论。

于 2016-07-17T10:27:02.100 回答
1

我建议你把那个逻辑移到Container Componentconnects UserMainenanceredux 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);

假设你有fetchUseractionCreator。

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

于 2016-07-17T11:14:25.013 回答