current position:Home>React usestate storage function

React usestate storage function

2022-06-24 09:34:58TA_ WORLD

React useState Storage function

Wrong writing

Use useState Store a function

const [callback,setCallback] = useState(
	() => {
     alert('init') }
)

Click button , Modify the function

<button onClick={() => setCallback( () =>alert('set') )}></button>

The above code will cause problems :

  • A pop-up window will appear when the component is rendered (‘init’)
  • A pop-up window will appear when you click the button (‘set’)

analysis :

This is actually useState Another way of writing , If at first state It needs to be obtained by complex calculation , You can pass in a function , Calculate in the function and return the initial state, This function is called only at the initial rendering time

const [state, setState] = useState(() => {
    
  const initialState = someExpensiveComputation(props);
  return initialState;
});

Write it correctly

const [callback,setCallback] = useState(() => () => {
    alert('init') 
})
<button onClick={
    () => setCallback( () => () =>alert('set') )}></button>

copyright notice
author[TA_ WORLD],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/175/202206240811463932.html

Random recommended