尽管传递了一个空数组,但当我尝试更新全局状态时,useEffect仍然会产生一个无限循环。我尝试过不传递空数组,添加依赖项,甚至尝试过在组件内部使用useState钩子,但似乎什么都不起作用。API调用没有任何问题,当我删除函数以更新状态时,没有循环。当我在代码中的其他地方这样做时,一切都很好。这是正在调用的useEffect功能组件。
const Posts = () => {
const [{auth}] = useAuth();
const [{profile},, setPosts] = useProfile();
const {getPostsByUser} = PostApi()
useEffect(() => {
const fetch = async () => {
const response = await getPostsByUser(auth.user._id, auth.token)
setPosts(response)
}
fetch()
}, [])
console.log(profile)
return(
<div className="User-Post">
<div className="New-Post">
<NewPost />
</div>
<div className="User-Posts-Content">
{
profile.posts ? profile.posts.map((item, key) => {
return <Post post={item} />
}) : null
}
</div>
</div>
)
}
这是useProfile挂钩:
const useProfile = () => {
const [{...profile}, setState] = useStore()
const setPosts = posts => {
setState(state => ({
...state,
profile: {
...state.profile,
posts: posts
}
}))
}
return [profile, setPosts]
}
这里是全球商店:
function makeStore() {
// Make a context for the store
const Context = React.createContext();
// Make a provider that takes an initialValue
const Provider = ({ initialValue, children }) => {
// Make a new state instance (could even use immer here!)
const [state, setState] = useState(initialValue);
// Memoize the context value to update when the state does
const contextValue = useMemo(() => [state, setState], [state]);
// Provide the store to children
return <Context.Provider value={contextValue}>{children}</Context.Provider>;
};
// A hook to help consume the store
const useStore = () => useContext(Context);
return { Provider, useStore };
}
这可能有助于
const [toggle, setToggle] = useState(false);
useEffect(() => {
const fetch = async () => {
const response = await getPostsByUser(auth.user._id, auth.token)
setPosts(response)
}
fetch()
}, toggle)
在需要时使用此结构