首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何避免使用useReducer([state,dispatch])和useContext进行无用的重新渲染?

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

Stack Overflow用户
提问于 2019-05-30 04:45:11
回答 1查看 6.7K关注 0票数 7

当使用多个useReducers时,每个组件都使用一部分状态渲染器。

代码语言:javascript
复制
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;

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

EN

回答 1

Stack Overflow用户

发布于 2019-05-30 04:54:09

如果useStateuseReducer状态发生更改,则组件将被更新,这在组件本身中是无法阻止的。

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

代码语言:javascript
复制
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具有相同的用途,以便从存储中提取所需的属性,并将它们映射到连接的组件属性。

票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56368252

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档