FooBlock
仅通过foo更改重新呈现什么内容
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])
但是看起来有点奇怪。有什么更好的方法吗?
答案 0 :(得分:0)
您不需要在组件内部创建组件。您只需将其编写在组件外部,然后将prop传递给它即可。
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>
}