React: Concept: Hook: Setter

 28th February 2021 at 10:17am

useState 返回的 setter,并不自动合并 object 字段

function Counter({initialCount}) {
  const [state, setState] = useState({a: 1, b: 2});
	
	function handleClick() {
	  // useState does not automatically merge update objects like class components do.
		// You should merge it manually with object spread or Object.assign
	  setState(prevState => {
		  a: 2, ...prevState
		})
	}
	
  return (
    <>
      Count: {count}
      <button onClick={handleClick}>Set A to 2</button>
    </>
  );
}

如果 state 变量的初始值需要复杂计算,不适合将它放在函数组件函数体中时(每次 render 时都会计算),应该放进 useState 的函数形式中:

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