当使用多个 useReducers 时,每个组件都会使用部分状态重新渲染。
import React, { useContext } from 'react'
import Store from '../store'
import { setName } from "../actions/nameActions"
const Name = () => {
const { state: { nameReducer: { name } }, dispatch } = useContext(Store)
const handleInput = ({ target: { value } }) => { dispatch(setName(value)) }
console.log('useless rerender if other part (not name) of state is changed');
return <div>
<p>{name}</p>
<input value={name} onChange={handleInput} />
</div>
}
export default Name;
如何避免这种无用的重新渲染?
If useState
or useReducer
状态改变,组件更新,组件本身没有办法阻止这种情况。
应防止在依赖于部分状态的子组件中重新渲染,例如通过使其纯净:
const NameContainer = () => {
const { state: { nameReducer: { name } }, dispatch } = useContext(Store)
return <Name name={name} dispatch={dispatch}/>;
}
const Name = React.memo(({ name, dispatch }) => {
const handleInput = ({ target: { value } }) => { dispatch(setName(value)) }
return <div>
<p>{name}</p>
<input value={name} onChange={handleInput} />
</div>
});
NameContainer
可以重写为 HOC 并起到与 Redux 相同的作用connect
,从存储中提取所需的属性并将它们映射到连接的组件道具。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)