如何使用 useReducer([state,dispatch]) 和 useContext 避免无用的重新渲染?

IT技术 reactjs react-hooks
2021-05-07 11:51:49

当使用多个 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;

如何避免这种无用的重新渲染?

1个回答

如果useStateuseReducer状态发生变化,则组件会更新,组件本身无法阻止这种情况。

在依赖于部分状态的子组件中应该防止重新渲染,例如通过使其纯:

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,从存储中提取所需的属性并将它们映射到连接的组件 props。