useEffect无限循环

时间:2019-10-27 00:19:17

标签: reactjs loops react-hooks

尽管传递了一个空数组,当我尝试更新全局状态时,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 };
}

1 个答案:

答案 0 :(得分:0)

这可能会帮助

  const [toggle, setToggle] = useState(false);
   useEffect(() => {
        const fetch = async () => {
            const response = await getPostsByUser(auth.user._id, auth.token)
            setPosts(response)
        }
        fetch()
    }, toggle)

在需要时使用此结构