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



如何设置加载(由上层函数返回(以便我可以在组件.js中使用它?(请参阅代码中的注释(

控制器.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>
}
}

首先,我将修改控制器.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>
}
}

按如下方式更新组件.js文件。

文件:组件.js

export default function component() {
const { setLoading, loading } = controller.postRender();
return (
<Wrapper onClick={() => setLoading(!loading)}>
</Wrapper>
}
}

控制器中.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?
}

相关内容

  • 没有找到相关文章

最新更新