[英]setState from the function in external file React Hooks
考慮一下:
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>
)
}
我在這里看到了一些類似的問題/答案,但是使用了Class
組件,但是如何使用 Hooks 像這樣 setState 呢?
PS:我需要使用 useImperativeHandle 來實現我的其他邏輯
您可以移動 function,但您必須將setContainerValue
作為參數傳遞給它:
export const someFunc(setContainerState => {
setContainerState({value: "string"});
};
不需要useImperativeHandle
,直接在Container
中調用someFunc
即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.