Reactjs 我可以从React上下文(useContext)中记忆setter函数吗
我正在尝试使用Reactjs 我可以从React上下文(useContext)中记忆setter函数吗,reactjs,react-hooks,Reactjs,React Hooks,我正在尝试使用useffect在安装组件时获取数据,如下所示: useEffect(() => { axios.get(myUrl) .then(response => { setName(response.name); setAge(response.age); }).catch(error => { console.log(error); });
useffect
在安装组件时获取数据,如下所示:
useEffect(() => {
axios.get(myUrl)
.then(response => {
setName(response.name);
setAge(response.age);
}).catch(error => {
console.log(error);
});
}, [myUrl, setName, setAge]);
import MyContext from './context';
const MyComponent = props => {
const {
setName,
setAge
} = useContext(MyContext);
setName
和setAge
来自以下上下文:
useEffect(() => {
axios.get(myUrl)
.then(response => {
setName(response.name);
setAge(response.age);
}).catch(error => {
console.log(error);
});
}, [myUrl, setName, setAge]);
import MyContext from './context';
const MyComponent = props => {
const {
setName,
setAge
} = useContext(MyContext);
这个问题是函数、数组和对象在useffect
调用中都注册为“已更改”的依赖项,因此它最终会进入一个无限循环,在这个循环中它会一次又一次地获取数据。我可以从上下文中记忆一个函数,以便它知道只调用该效果一次吗
注意:我的上下文的使用者比这个组件高出几个级别,所以我猜在那里我无能为力 我认为您需要定义绑定到userId之类的东西。
这将为您提供一个稳定的标识符,该标识符只有在必要时才会更改。无法从上下文中记忆函数 也就是说,您可以通过从库中导入自定义钩子,或者只需查看并自己声明它,就可以为
useMount
使用自定义钩子。下面显示了如何定义useMount
和useffectOnce
,然后利用useMount
作为解决方法:
const useEffectOnce = (effect) => {
useEffect(effect, []);
};
const useMount = (fn) => {
useEffectOnce(() => {
fn();
});
};
useMount(() => {
axios.get(myUrl)
.then(response => {
setName(response.name);
setAge(response.age);
}).catch(error => {
console.log(error);
});
});
使用这种方法,您不需要更改上下文声明、上下文提供程序或上下文使用者的任何内容。我猜您的意思是定义基于useContext的上下文。是吗?是的。您需要使用在多个组件之间共享数据(您的案例中的用户信息)。看起来像是你的案子。就我个人而言,我远离钩子,使用mobx+的可观察对象,我更喜欢OOP-React组件。