首页 > 解决方案 > 我可以在不违反 React Hooks 规则的情况下解构 React 上下文以在 useEffect 中使用吗?

问题描述

问题的症结在于:如何使用上下文中的数据来触发 useEffect?

据我了解钩子的规则,它们都必须在函数的顶部,所以这可能是违规的,对吧?

export const MyComponent = () => {
    const appContext = useContext(AppContext);
    const {dispatch, state} = appContext;  // destructuring in front of another hook
    useEffect(()=>{
        // Do something with state here
    }, [state]);
}

在不直接将状态作为道具传递的情况下,我能想到的唯一另一种方法是使用本地组件状态,但这对我来说真的很可怕。

export const MyComponent = () => {
    const appContext = useContext(AppContext);
    const [state, setState] = useState({});
    useEffect(()=>{
        const {_state} = appContext;
        setState(_state);
    },[]);
    useEffect(()=>{
        // Do something with state here
    }, [state]);

    const {dispatch} = appContext;
}

我感谢所有建议。先感谢您。

标签: reactjsreact-hooks

解决方案


在两个钩子之间有一个破坏语句并不违反钩子的规则。钩子状态的规则是什么Only Call Hooks at the Top Level而不是什么Only Call Hooks at the Top of function

这个想法是你没有钩子loops, conditions, or nested functions

您需要注意的是,在组件的每次渲染中,钩子的总数保持不变。

因此下面的代码是一个完全有效且正确的代码

export const MyComponent = () => {
    const appContext = useContext(AppContext);
    const {dispatch, state} = appContext;  
    useEffect(()=>{
        // Do something with state here
    }, [state]);
}

推荐阅读