Javascript 从外部文件中的函数设置状态
考虑这一点:Javascript 从外部文件中的函数设置状态,javascript,reactjs,react-hooks,Javascript,Reactjs,React Hooks,考虑这一点: import { someFunc } from "./someFunc"; const Container = () => { const [containerState, setContainerState] = useReducer( (state, newState) => ({ ...state, ...newState }), { value: "", text: "some text here" }); // I want
import { someFunc } from "./someFunc";
const Container = () => {
const [containerState, setContainerState] = useReducer(
(state, newState) => ({ ...state, ...newState }),
{ value: "", text: "some text here" });
// I want to move the function bellow into external file (see the "import" above)
// const someFunc = () => {
// setContainerState({value: "string"})
// }
// like this:
// const extFunc = someFunc();
// useImperativeHandle(ref, () => ({
// someFunc()
// }));
// but if I do so, I'll get "setContainerState" is undefined
// how can I move this function to external file?
// it is long and it makes my component messy and hard to read
return (
<h1>Test Title</h1>
<button onClick={someFunc}>click me</button>
)
}
我在这里看到了一些类似的问题/答案,但是使用类组件,但是如何使用钩子设置这样的状态
PS:我需要使用UseImperialiveHandle来实现我的其他逻辑您可以移动该函数,但必须将setContainerValue作为参数传递给它:
export const someFunc(setContainerState => {
setContainerState({value: "string"});
};
不需要UseImperializeHandle,只需在容器中直接调用someFunc。如果我使用useReducer处理容器组件内setContainerState的状态更改,该方法安全吗?@T.J.Crowder谢谢you@jay_dtr-是的,应该很好。重要的是钩子在调用组件的过程中被调用。如果是因为你的组件调用了一个调用钩子的函数,那也没关系。