通过操作进行Redux状态访问,我应该使商店成为全局商店吗?

时间:2018-10-24 21:32:37

标签: reactjs redux redux-thunk

我对redux还是很陌生,这是我商店的简化版本:

store: {
  userID: 1234,
  userData: { // get's fetch-ed from api
    foo,
    bar,
    ...
}

当我更改userID时,我想对userData进行自动更新,我为它找到了一个名为redux-thunk的库,它可以使dispatch-es异步(我正在获取数据),但是对于获取URL,我需要userID从商店中,我无法直接从action / updateUser访问它。

我每次调用它时都应将其传递给动作 dispatch(updateUser(store.getState().userID))吗?

1 个答案:

答案 0 :(得分:1)

我不确定我是否完全理解这个问题,但是在我看来,您的方向正确,但可能想重新考虑一下商店的结构。如果您有定义减速器的代码,那么在此处以及使用connect来访问组件属性中的此数据的位置将很有帮助。

缺少,这是我的建议。

听起来您正在寻找能够显示用户个人资料,在用户个人资料之间切换的功能。在这种情况下,建议您使用用户列表而不是单个被覆盖的用户对象来构建商店。看起来像这样:

{ 
  users: [{ id: '123', name: 'Hello' }, { id: '234', name: 'Goodbye' }],
  currentUserId: '123'
}

在这种情况下,要切换您在特定页面上显示的用户(或您登录的用户),只需更改组件中选择的用户,而不是更新商店以用新用户覆盖user。如果UI元素在不更新URL的情况下更新当前用户(即调用dispatch(updateCurrentUserId('234'))的情况),则您的组件应根据以下内容从商店的users键中选择用户:< / p>

const MyComponent = ({ user }) => (
  <div>User name is { user.name }</div>
);

const mapStateToProps = ({ users, currentUserId ) => ({
  user: users.find(u => u.id === currentUserId)
});

export default connect(mapStateToProps)(MyComponent);

这样,要切换代表哪个用户,您只需要更改商店中的currentUserId

假设您已经从API获取了用户列表。如果您一次要获取一个,则确实可以使用redux thunk。我仍然建议将用户存储为列表,以便您可以轻松地在他们之间切换。在这种情况下,您的团伙想要从商店中抓住用户(如果存在的话),或者从那里获取用户。像这样:

// Alternately, you could pass *no* argument, and grab currentUserId
// from state like users below
const getUser = userId => (dispatch, getState) => {
  const localUsers = getState().users;
  const localUser = localUsers.find(u => u.id === userId);

  if (localUser) {
    // Because the user is in the store, we just need to point the frontend
    // to the right user.
    dispatch(updateCurrentUserId(userId));

  } else {
    // Fetch the user, add them to the store, and then point to them.
    fetch(`whatever.com/users/${userId}`)
      .then(response => {
         dispatch(addUser(response.data));
         dispatch(updateCurrentUserId(userId));
      }).catch(err => /* do something */);
  }
}

此功能可让您根据用户是否存在于数据中来有条件地进行异步操作。但是,与您的设计不同,您不会在新用户到来时覆盖当前用户。

请注意,您也可以在没有currentUserId的情况下执行此操作,例如,仅从URL中解析用户ID。

相关问题