[英]useEffect infinite loop
盡管傳遞了一個空數組,但當我嘗試更新全局 state 時,useEffect 仍然會產生無限循環。 我嘗試過不傳遞空數組,添加依賴項,甚至嘗試在組件本身內部使用 useState 掛鈎,但似乎沒有任何效果。 API 調用沒有任何問題,當我刪除 function 以更新 state 時,沒有循環。 當我在代碼中的其他任何地方執行此操作時,一切正常。 這是正在調用的功能組件 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)
在需要時使用此結構
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.