使用useReducer Hook时反应中的重新渲染次数过多

时间:2020-09-24 18:13:41

标签: reactjs react-hooks

使用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 个答案:

答案 0 :(得分:4)

渲染组件时。您没有单击就调用了函数dispath。您应该将回调传递给事件onClick:

正确更新操作可以使其起作用:

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