Skip to content
本页目录

不要关注

代码题

Q: useState 中的值是个对象,改变对象中的值,demo 会渲染吗?如果用 React.memo() 包裹住呢

jsx
function demo() {
    const [data, setData] = useState({ foo: { bar: { baz: 1 } } });
    return <div onClick={() => setData(1)}>改变</div>;
}

A:

state 拆分过多

useState 目前的一种实践,是将变量名打扁,而非像类组件一样写在一个 State 对象里

jsx
class ClassComponent extends React.PureComponent {
  state = {
    left: 0,
    top: 0,
    width: 100,
    height: 100
  };
}

// VS

function FunctionComponent {
  const [left,setLeft] = useState(0)
  const [top,setTop] = useState(0)
  const [width,setWidth] = useState(100)
  const [height,setHeight] = useState(100)
}

实际上在函数式组件中也可以聚合管理 State

jsx
function FunctionComponent() {
    const [state, setState] = useState({
        left: 0,
        top: 0,
        width: 100,
        height: 100,
    });
}

只是更新的时候,不再会自动 merge ,而需要使用 ...state 语法(解构)

jsx
setState((state) => ({ ...state, left: e.pageX, top: e.pageY }));

ahooks 里是怎么操作的?