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

Lye*_*yes 1 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>
)
}
Run Code Online (Sandbox Code Playgroud)

我仅在用户单击按钮时才调度操作,因此我无法弄清楚它是如何导致多次渲染的。

任何解释都是宝贵的

Vie*_*inh 5

渲染组件时。您在dispath没有任何点击的情况下调用了函数。您应该将回调传递给 onClick 事件:

更新正确操作使其工作:

   <Button onClick={() => dispatch({type: 'LOW'})}>Increment low</Button>
Run Code Online (Sandbox Code Playgroud)