这是我第一次使用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) => {
return {
...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”地图中(忽略此部分),并更新我的currentUser数据增加了他的总保存量。
2-如果动作类型为“未保存”,则相反。
我的问题是我需要将参数“ reviews”传递给减速器。例如,如果我有此功能可从数据库中获取“额外数据”:
const fetchReviews = async (bookId) => {
// Get a list of reviews from the db
const reviews = await db.fetchReviews(bookId);
return reviews;
}
我这样使用它:
const reviews = await fetchReviews(bookId);
如何将评论作为参数传递给reducer?
dispatch({ type: saved ? "save" : "unsave" });
谢谢。
答案 0 :(得分:1)
您已经将一个对象传递到dispatch()
,并且没有阻止您将payload
与type
一起添加的情况:
dispatch({
type: saved ? "save" : "unsave",
payload: reviews,
});
通过这种方式,您可以访问化简(action.payload
)中的评论。
const reducer = (state, action) => {
// action has `type` and `payload` properties
}
答案 1 :(得分:1)
当调用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;
}
}