如何从效果外部使用React Hooks设置状态?

时间:2020-06-29 08:44:23

标签: reactjs react-hooks

如何设置加载(由上限作用域函数返回),以便可以在component.js中使用它?(请参见代码中的注释)

controller.js

const controller = {
    postRender: () => {
        const otherVar = useState(0);
        const loading = useState(false);
        
        useEffect(() => {
            // this is automatically called on every render and in fact accepts variables from postRender() scope
            otherVar(1);
        }, [other_var])

        const setLoading = (isLoaded) => {
            // this is called in component.js
            // how do I set loading (returned by the upper scope function) so I can use it in component.js?
        }

        return {
                otherVar,
                loading,
                setLoading
        };
    }
}

export default controller;

component.js

export default function component() {

    const { loading } = controller.postRender();

    return (
        <Wrapper onClick="setLoading(!loading)">
        </Wrapper>

   }
}

2 个答案:

答案 0 :(得分:1)

如下更新您的 component.js 文件。

文件: component.js

export default function component() {

    const { setLoading, loading } = controller.postRender();

    return (
        <Wrapper onClick={() => setLoading(!loading)}>
        </Wrapper>

   }
}

在您的 controller.js 文件中,如下更改加载变量

更新

const loading = useState(false);

const [loading, setLoading] = useState(false);

并删除此功能

const setLoading = (isLoaded) => {
            // this is called in component.js
            // how do I set loading (returned by the upper scope function) so I can use it in component.js?
}

答案 1 :(得分:1)

首先,我将修改 controller.js ,并使其成为适当的自定义钩子。

类似这样的东西:

import { useState, useEffect } from "react";
const useDragon = () => {
  const [otherState, setOtherState] = useState(0);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setOtherState(1);
  }, [setOtherState]);

  const changeLoading = () => {
    // assuming you want to toggle the loading
    setLoading(prevLoading => !prevLoading)
  };

  return {
    otherState,
    loading,
    changeLoading
  };
};

export default useDragon;

,在组件中,您可以通过以下方式使用它:

export default function component() {

    const { otherState, loading, changeLoading } = useDragon();

    return (
        <Wrapper onClick={changeLoading}>
        </Wrapper>

   }
}