reactjs - 我可以在不违反 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]);
}
推荐阅读
- flutter - Flutter 中的 PKCS1 加密在没有反射的情况下将无法工作
- google-apps-script - Google Apps 脚本 - 更改 Gmail 中单个电子邮件的标签
- c# - 带有 DataContractJsonSerializer 的可选字段(如何更改默认值)
- ios - 如何在右侧的 UIButton 上添加图像并且 contentMode 不适用于图像?
- c# - 将 TextBox 的值填充到特定的文本框
- nest - Elasticsearch NEST Buckets 内部 Buckets 聚合
- c# - C# 将方法隐式转换为自定义类型
- r - 条件变异和向量
- git - 如果有上游更改,Git 预提交钩子会阻止提交
- php - MySql 查询:不要等待结果