这是我第一次使用 useReducer() 钩子,我面临一个问题,我需要向它传递一个值作为参数。这是我的减速器的样子: const memoizedReducer = useCallback((state, action) => { switch (action.type) { case "save": const refreshedBookData = { ...state.bookData, ...(state.bookData.totalSaves >= 0 && { totalSaves: state.bookData.totalSaves + 1, }), isSaved: true, }; // Add the new book data to a Map which I have in a Context provider currentUser.addBookToVisitedBooks(bookId, refreshedBookData); // Update my context provider data currentUser.setData((prevCurrentUserData) => { eturn { ...prevCurrentUserData, ...(prevCurrentUserData.totalSaves >= 0 && { totalSaves: prevCurrentUserData.totalSaves + 1, }), }; }); return refreshedBookData; case "unsave": const refreshedBookData = { ...state.bookData, ...(state.otheBookData.totalSaves >= 0 && { totalSaves: state.bookData.totalSaves - 1, }), isSaved: false, }; // Add the new book data to a Map which I have in a Context provider currentUser.addBookToVisitedBooks(bookId, refreshedBookData); // Update my context provider data currentUser.setData((prevCurrentUserData) => { return { ...prevCurrentUserData, ...(prevCurrentUserData.totalSaves > 0 && { totalSaves: prevCurrentUserData.totalSaves - 1, }), }; }); return refreshedBookData; default: return state;});const [{ bookData }, dispatch] = useReducer(memoizedReducer, { bookData: params?.bookData});正如你所看到的,我正在做的是:1-如果操作类型是“保存”,则增加书籍的总保存次数,将新书籍数据添加到我在上下文中拥有的“visitedBooks”地图(忽略这部分),并更新我的当前用户数据,增加他的总节省。2-如果操作类型是“未保存”,我会执行相反的操作。
2 回答
MMTTMM
TA贡献1869条经验 获得超4个赞
您已经将一个对象传递给dispatch()并且没有什么可以阻止您添加 apayload和type:
dispatch({
type: saved ? "save" : "unsave",
payload: reviews,
});
这样您就可以访问您的减速器 ( ) 中的评论action.payload。
const reducer = (state, action) => {
// action has `type` and `payload` properties
}
哔哔one
TA贡献1854条经验 获得超8个赞
当您调用该dispatch方法时,您将传递一个具有该type字段的对象。这个对象的格式实际上是由你来定义的。如果您需要传递以外的参数也type可以随意这样做。
例如
const reviews = {....} ; /// reviews
dispatch({ type: 'save', payload: reviews });
然后在你的减速器中你可以得到payload对象
// Reducer
const reducer = (state, action) => {
switch (action.type) {
case 'save':
const reviews = action.payload;
//.....
break;
}
}
添加回答
举报
0/150
提交
取消