如何使用 useReducer([state,dispatch]) 和 useContext 避免无用的重新渲染? [英] How to avoid useless rerender using useReducer([state,dispatch]) and useContext?
问题描述
当使用多个 useReducers 时,每个组件都会重新渲染一部分状态.
import React, { useContext } from 'react'从../store"导入商店从../actions/nameActions"导入 { setName }const 名称 = () =>{const { state: { nameReducer: { name } }, dispatch } = useContext(Store)const handleInput = ({ target: { value } }) =>{调度(设置名称(值))}console.log('如果状态的其他部分(不是名称)被改变,则无用的重新渲染');返回 <p>{名称}</p><input value={name} onChange={handleInput}/>}导出默认名称;
如何避免这种无用的重新渲染?
如果 useState
或 useReducer
状态改变,则组件更新,没有办法阻止在组件本身中.
在依赖于部分状态的子组件中应该防止重新渲染,例如通过使其纯净:
const NameContainer = () =>{const { state: { nameReducer: { name } }, dispatch } = useContext(Store)return ;}const Name = React.memo(({ name, dispatch }) => {const handleInput = ({ target: { value } }) =>{调度(设置名称(值))}返回 <p>{名称}</p><input value={name} onChange={handleInput}/>});
NameContainer
可以重写为 HOC 并用于与 Redux connect
相同的目的,从存储中提取所需的属性并将它们映射到连接的组件 props.>
When using multiple useReducers every component using a part of the state rerenders.
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;
How to avoid this useless rerendering?
If useState
or useReducer
state changes, the component is updated, there is no way to prevent this in the component itself.
Re-render should be prevented in child component that depends on partial state, e.g. by making it pure:
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
can be rewritten to a HOC and serve the same purpose as Redux connect
, to extract needed properties from a store and map them to connected component props.
这篇关于如何使用 useReducer([state,dispatch]) 和 useContext 避免无用的重新渲染?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!