如何映射存储中的对象(使用 redux-thunk)

How to map objects in store (with redux-thunk)

你好,我想通过redux,redux-thunk迭代数组中的一个对象

问题是,全局状态(存储)不能迭代Array.map()

这里是教程的例子https://codesandbox.io/s/modest-pike-q0449

这是我的版本https://codesandbox.io/s/redux-thunk-fetch-6wsr8

区别是...

异步操作创建者

axios.get('https://jsonplaceholder.typicode.com/todos/1') //tutorial: return 1 object
axios.get('https://jsonplaceholder.typicode.com/todos')   //my experimental: return array of object

UI组件

const dispatch = useDispatch();

// Tutorial------------------------------
{content.data && (
  <ul>
    <li>{content.data.id}</li>
    <li>{content.data.title}</li>
  </ul>
)}

// My Experimental------------------------ ERROR: content.map is not a function.
<ul>
  {content.map(todo => (
    <li key={todo.id}>{todo.title}</li>
  ))}
</ul>

我已经搜索了解决方案。我找到了 React.Children 但我不确定在这种情况下是否使用它。

谢谢

这就是你需要的

const content = useSelector(state => state.data || []);

您可以通过在初始状态

中将数据初始化为[]来摆脱默认的空数组
function reducer(state = { data: [] }, action) {

}

// now access data
const content = useSelector(state => state.data);