请按照下面的代码片段,当我单击任何按钮(添加、编辑、删除)时,我的所有组件都会重新渲染,包括Title
没有props
或的组件stats
。如果我有几个组件可能没问题,但假设我有超过15 个或更多的组件来获取/保存数据,这样可以还是应该避免?
我尝试使用useCallback
钩子(使用handleRemove),但显然这不能按预期工作。
const Button = ({ title, count, onClick }) => {
console.log(`Rendering ${title}`)
return (
<button onClick={onClick}>
{title} ({count})
</button>
)
}
const Header = () => {
console.log("Rendering Title")
return <h1>App Title</h1>
}
const Parent = () => {
const [add, setAdd] = React.useState(0)
const [edit, setEdit] = React.useState(0)
const [remove, setRemove] = React.useState(0)
const handleAdd = () => setAdd(add + 1)
const handleEdit = () => setEdit(edit + 1)
const handleRemove = React.useCallback(() => {
setRemove(remove + 1)
}, [remove])
return (
<React.Fragment>
<Header />
<Button title="Add" onClick={handleAdd} count={add} />
<Button title="Edit" onClick={handleEdit} count={edit} />
<Button title="Remove" onClick={handleRemove} count={remove} />
</React.Fragment>
)
}
function App() {
return (
<div className="App">
<Parent />
<button onClick={console.clear}>Clear log</button>
</div>
)
}
ReactDOM.render( <App /> , document.getElementById('root'))
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div id="root"></div>