我创建一个功能组件,并在其中声明一些变量。
const Foo = (props) => {
let instanceVariable = null;
const selectValue = (value) => {
instanceVariable = value;
}
const proccessVariable = () => {
// Use instanceVariable and do some task
}
return(
<SelectionOption onChange={selectValue} />
);
}
I observe that whenever parent component of Foo
is re-render or sometime Foo
itself re-render instanceVariable
set back to null
instead of this I want to save selectedValue
init and proccess it later on proccessVariable()
method.
If I set instanceVariable
as state
it will work and there is no need of state to just hold the selected value.
I know useEffect(()=>{}, [])
only run one time but how can I declare instanceVariable
there and use it in other functions.
您能告诉我我做错了吗?
Since you declare a variable directly in your functional component, its value is reset everytime your component re-renders. You can make use of
useRef
to declare instance variables in functional component