i仅使用foo cange
才能FooBlock
rerender export function FooBarComponent() {
const [foo, setFoo] = useState(1)
const [bar, setBar] = useState(1)
const FooBlock = () => {
console.log("render", foo)
return <div>{foo}</div>
}
return <div>
<button onClick={() => setFoo(x => x + 1)}>foo</button> {foo}
<button onClick={() => setBar(x => x + 1)}>bar</button> {bar}
<FooBlock/>
</div>
}
我可以做这样的事情
const FooBlock = useMemo(() => React.memo(() => {
console.log("render", foo)
return <div>{foo}</div>
}), [foo])
,但看起来有些怪异。有更好的方法吗?
您不需要在组件中创建组件。您可以简单地将其写入组件并将道具传递给它。
const FooBlock = ({foo}) => {
console.log("render", foo)
return <div>{foo}</div>
}
export function FooBarComponent() {
const [foo, setFoo] = useState(1)
const [bar, setBar] = useState(1)
return <div>
<button onClick={() => setFoo(x => x + 1)}>foo</button> {foo}
<button onClick={() => setBar(x => x + 1)}>bar</button> {bar}
<FooBlock foo={foo}/>
</div>
}