我可以在不违反 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;
}

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

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

最新更新