【发布时间】: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