我可以在不违反 React Hooks 规则的情况下解构 React Context 以在 useEffect 中使用吗?

Can I destructure a React Context for use in useEffect without violating the rules of React Hooks?

问题的症结在于:如何使用上下文中的数据来触发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]);
}

我能想到的不直接将状态作为 prop 传递的唯一其他方法是使用本地组件状态,但这对我来说真的很糟糕。

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;
}

我感谢所有建议。提前谢谢你。

在两个钩子之间有一个破坏语句并不违反钩子规则。挂钩状态的规则是 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]);
}