2 回答
TA贡献1827条经验 获得超8个赞
调用useState()钩子的setter 方法的一个副作用是,这样做会触发组件重新渲染。
避免冗余重新渲染的一种解决方案是合并您的组件状态,如下所示:
function functionalComponent() {
/* Merge both values into common "state object */
const [{ loaded, title }, setState] = React.useState({
loaded : null,
title : "inital title"
});
React.useEffect(() => {
/*
Single call to setState triggers on re-render only. The
value of "new title" for title could have been set in the
inital state, however I set it here to show how combined
state can be updated with a single call to setState()
*/
setState({ loaded : true, title : "new title" })
/*
setLoaded(true);
setTitle(title);
*/
}, []);
/* Use loaded and title variables as needed during render */
return <div>{ loaded } - { title }</div>
}
添加回答
举报