首页 > 解决方案 > 如何从 redux store 访问数据

问题描述

所以我想用 API 获取一些数据,然后将其存储到我的 Redux Store 中以便在任何地方使用它。

fetch 工作得很好,我的控制台向我显示 action 和 reducer 也在工作。

控制台捕获

但是在我的“列表”组件中,this.propsundefined(参见控制台捕获)在我的渲染方法和构造函数中。

为了简单起见,我制作了一个代码框:https ://codesandbox.io/embed/reduxcrypto-k16tz

我不知道该怎么办。

谢谢你的帮助

标签: reactjsreduxreact-reduxredux-thunk

解决方案


你的 reducer 中的这个东西会删除响应内容:

cryptoDataCopy = {
  currency: action.currency // there is no currency field in your action
  // probably you want to use action.payload and save it to crypto field
  // since List tries to use crypto field
  // crypto: action.payload
};

此外,您没有在减速器中使用操作有效负载,而只是复制以前的状态。应该有一些东西可以将有效载荷放入 state.crypto:

...
var cryptoDataCopy = { ...cryptoData, crypto: '123' };
  // cryptoDataCopy.currency = {
  //   currency: action.currency
  // }

  return {
    ...cryptoData,
    currency: action.currency,  // actually, there is no such field in your action
    crypto: action.payload
  };

而且您的请求不会返回任何内容。您可以添加 catch 以查看有关失败请求的日志:

.then(response => {
  ...
}).catch(
  () => {
    console.log('no response')
  }
);

推荐阅读