【问题标题】:Too many re-renders in react when using useReducer Hook使用 useReducer Hook 时反应中的重新渲染过多
【发布时间】:2020-09-25 02:31:43
【问题描述】:

我在使用 useReducer react hook 时遇到了一个奇怪的问题,我知道错误的根源,但我不知道为什么它会出现在我的代码中。

import React, { useReducer } from 'react'

import { Button } from 'react-bootstrap'


export default function User() {

const initialState = {
    lowScore: 0,
    mediumScore: 0,
    hightScore: 0 
}

const reducer = (state, action) => {
    switch(action.type){
        case 'LOW':
            return {
                ...state,
                lowScore: state.lowScore + 1
            }
        case 'MEDIUM':
            return {
                ...state,
                mediumScore: state.mediumScore + 1
            }
        case 'HIGH':
            return {
                ...state,
                hightScore: state.hightScore + 1
            }
        default:
            return state
    }
}

const [state, dispatch] = useReducer(reducer, initialState)

return (
    <div>
        Low: { state.lowScore }, medium: { state.mediumScore }, hight: { state.hightScore } 
        <Button onClick={dispatch('LOW')}>Increment low</Button>
        <Button >Increment medium</Button>
        <Button >Increment hight</Button>
    </div>
)
}

我只在用户点击按钮时调度动作,所以我无法弄清楚它是如何导致多次渲染的。

任何解释都是宝贵的

【问题讨论】:

  • 一个组件将在以下情况下重新渲染:1)它的道具改变,2)它的状态改变,3)它的父组件重新渲染。很难从您提供的代码中诊断出这三个中的哪一个(除了您显示的调度操作)
  • @rantao dispatch action 会更新状态,为什么很难知道是哪一个导致了重新渲染?
  • 我的意思是,您的组件可能重新呈现的原因不止一个,而且您只显示了标识三个原因之一的代码
  • @ⵍⵢⴻⵙ 以下答案是否解决了您的问题?如果是这样,请选择它作为正确答案(单击答案旁边的复选标记)以关闭此问题并奖励声誉积分。那会帮助我们。否则,请在答案下添加评论或使用更多信息更新您的问题,其他人将尝试提供帮助。 非常感谢!

标签: reactjs react-hooks


【解决方案1】:

当你渲染组件时。您无需任何点击就调用了函数dispath。您应该将回调传递给事件 onClick:

正确更新操作使其工作:

   <Button onClick={() => dispatch({type: 'LOW'})}>Increment low</Button>

【讨论】:

  • 为了让它工作,你应该调度一个具有属性类型的对象 - () =&gt; dispatch({type:'LOW'})
  • @VietDinh 我的错,谢谢,我还是不明白 react 的行为,dispatch('LOW') 会导致多次重新渲染吗?
  • 渲染组件时。您已将函数 dispath('LOW') 的结果添加到事件舔中。该函数将被调用。然后 dispath 将为组件返回一个新状态。如果返回状态没有变化,函数组件将不会重新渲染。但是,react 可能有语法检测,某些情况下会在返回函数中将无限循环设为“始终调用 setState”。你的情况,它总是叫dispath。
  • 我刚刚遇到了同样的问题,有没有关于这种行为的文档。
猜你喜欢
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-18
  • 2020-09-07
  • 1970-01-01
  • 2020-08-20
相关资源
最近更新 更多