繁体   English   中英

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

[英]How to set state with React Hooks from outside an effect?

如何设置加载(由上面的 scope 函数返回)以便我可以在 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;

组件.js

export default function component() {

    const { loading } = controller.postRender();

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

   }
}

首先,我将修改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>

   }
}

如下更新您的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);

并删除此 function

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?
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM