问题描述
当我尝试调度从状态中获取所有最新帖子的动作时,它陷入无限循环。
我在useEffect依赖项数组中尝试了以下方法
-
Object.values(statePosts)
-
useDeepCompare(statePosts)
- 通过
dispatch
- 省略
dispatch
- 省略
statePosts
- 通过
statePosts
- 在
useCallback
中做同样的事情
很多建议来自here
我已验证数据在我的redux存储中正确更新。
我不知道为什么这种情况仍在发生
我的组件
const dispatch = useDispatch()
const { user } = useSelector((state) => state.user)
const { logs: statePosts } = useSelector((state) => state.actionPosts)
const useDeepCompare = (value) => {
const ref = useRef()
if (!_.isEqual(ref.current,value)) {
ref.current = value
}
return ref.current
}
useEffect(() => {
dispatch(getActionLogsRest(user.email))
},[user,dispatch,useDeepCompare(stateLogs)])
actionPosts createSlice
const slice = createSlice({
name: 'actionPosts',initialState: {
posts: [],},reducers: {
postsLoading: (state,{ payload }) => {
if (state.loading === 'idle') {
state.loading = 'pending'
}
},postsReceived: (state,{ payload }) => {
state.posts = payload
},})
export default slice.reducer
const { postsReceived,postsLoading } = slice.actions
export const getActionPostsRest = (email) => async (dispatch) => {
try {
dispatch(postsLoading())
const { data } = await getUserActionPostsByUser({ email })
dispatch(postsReceived(data.userActionPostsByUser))
return data.userActionPostsByUser
} catch (error) {
throw new Error(error.message)
}
}
解决方法
从依赖项中删除调度。
useEffect(() => {
dispatch(getActionLogsRest(user.email))
},[user,dispatch,useDeepCompare(stateLogs)])
您不能使用钩子作为依赖项,顺便说一句,ref.current在这里始终未定义
const useDeepCompare = (value) => {
const ref = useRef()
if (!_.isEqual(ref.current,value)) {
ref.current = value
}
return ref.current
}
因为useDeepCompare本质上是您在每次调用时(与ref一起)初始化的一个函数,所以它所做的只是返回value
。这就是循环开始的地方。