React-在纯函数中运行副作用



简介

我当前的用例要求将最新的状态更新存储在缓存中。由于状态更新是异步的,并且可能有很多组件并行更新同一个组件,因此将它们存储在useState或useReducer纯函数的主体中可能是一个不错的选择。

但是。。。副作用来了,挫败感开始了。我尝试过等待调度,创建自定义挂钩";useReducerWithCallback";,和其他东西,但我看不出我的问题的正确解决方案。

问题

我有一个模块usersCache.js,它为我提供了修改缓存的必要方法:

const cache = {};
export const insert = (id, data) => ...
export const get = (id) => ...
// and more stuff

当我进行状态更新时,我正在尝试更新此缓存。例如:

const currentUser = useContext(CurrentUserContext);

...
// Note: setData is just the state setter useState hook
currentUser.setData((prevData) => {
const newTotalFollowing = prevData.totalFollowing + 1;
usersCache.update(currentUser.data.id, { newTotalFollowing }); <---- SIDE EFFECT

return { ...prevData, totalFollowing: newTotalFollowing };
});

我的其他用户reducer中也有同样的东西

import { usersCache } from "../../services/firebase/api/users"
export default (otherUsers, action) => {   
switch (action.type) {
case "follow-user": {
const { userId, isFollowing } = action;
const prevUserData = otherUsers.get(userId);
const newTotalFollowers = prevUserData.totalFollowers + (isFollowing ? 1 : -1);
usersCache.update(userId, { totalFollowers: newTotalFollowers }); // merge update
return new Map([
...otherUsers,
[
userId,
{
...prevUserData,
totalFollowers: newTotalFollowers
]
]
);
}
...
}
}

就像在纯功能中一样,我们不应该产生副作用。。。有没有其他方法来处理这个问题?

注意:我没有使用Redux

您可以使用存储库模式和react钩子来检查这个完整的工作示例,以简化带有状态分派的异步操作。我知道你没有使用redux,但你可以使用useReducer钩子来调整这个例子,将其连接到你的React Context存储。

最新更新