代码大致逻辑如下, const b 基于 a 生成(实际上 a 是通过 props 传进来的),并传递给组件 Child.
根据输出可以注意到子组件 Child 被调用了两次.
怎么做才能避免 Child 不必要二次更新呢?
function createB(a) { return { a }; } export default function Index() { const [a, setA] = useState(0); const [b, setB] = useState(createB(a)); useEffect(() => { console.log('b', b); setB(createB(a)); }, [a]); return <Child b={b}></Child>; } function Child(props) { const b = props.b; useEffect(() => { console.log('child b', b); }, [b]); return <div>{b.a}</div>; }
输出
child b {a: 0} b {a: 0} child b {a: 0}
![]() | 1 aaronlam 2022-05-20 21:11:39 +08:00 ![]() React.memo 一下 Child 组件 |
![]() | 2 rabbbit OP 问题描述有点问题, 改一下应该是: 怎样才能避免 Index 没必要的二次调用 createB(a) ? createB 返回的是个树形结构,开销还蛮大的. |