如何让数据抓取与 Redux Toolkit 和 React Hooks 一起工作?
How to make data fetching work together with Redux Toolkit and React Hooks?
我正在尝试 Redux Toolkit 文档中的示例:
演示:https://codesandbox.io/s/nice-sound-1ybmf?file=/features/counter/Counter.js
而且有效。
然后我尝试the following also in the docs just to fetch some data and display on the page,使用
const fetchUsers = () => async (dispatch) => {
dispatch(usersLoading());
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
dispatch(usersReceived(data));
};
演示:https://codesandbox.io/s/zen-northcutt-lb4ww?file=/features/users/Users.js
但是 No reducer provided for key "users"
和 Store does not have a valid reducer.
会出错
如何让它发挥作用?而函数fetchUsers()
,它属于Users.js
还是usersSlice.js
,这个使用Redux Toolkit的数据获取机制是否还有其他需要改变的东西?
您已将用户操作的导出添加到用户切片,但您仍在整体导入 userSlice reducer 以创建您的商店。
export const { usersLoading, usersReceived } = usersSlice.actions
由于您没有导出切片,因此无法访问切片。您需要另外导出带有 export default usersSlice.reducer
的切片,以便 import usersReducer from "../features/users/usersSlice";
再次工作
我正在尝试 Redux Toolkit 文档中的示例:
演示:https://codesandbox.io/s/nice-sound-1ybmf?file=/features/counter/Counter.js
而且有效。
然后我尝试the following also in the docs just to fetch some data and display on the page,使用
const fetchUsers = () => async (dispatch) => {
dispatch(usersLoading());
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const data = await response.json();
dispatch(usersReceived(data));
};
演示:https://codesandbox.io/s/zen-northcutt-lb4ww?file=/features/users/Users.js
但是 No reducer provided for key "users"
和 Store does not have a valid reducer.
如何让它发挥作用?而函数fetchUsers()
,它属于Users.js
还是usersSlice.js
,这个使用Redux Toolkit的数据获取机制是否还有其他需要改变的东西?
您已将用户操作的导出添加到用户切片,但您仍在整体导入 userSlice reducer 以创建您的商店。
export const { usersLoading, usersReceived } = usersSlice.actions
由于您没有导出切片,因此无法访问切片。您需要另外导出带有 export default usersSlice.reducer
的切片,以便 import usersReducer from "../features/users/usersSlice";
再次工作