Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 我可以从React上下文(useContext)中记忆setter函数吗_Reactjs_React Hooks - Fatal编程技术网

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组件。