React JS 中 useReducer 钩子的意外行为

问题描述 投票:0回答:1

任何人都可以让我知道为什么我在这里得到两个控制台打印吗?

下面是我的代码:

import React, {useReducer} from 'react';

const Counter = () => {

    const initialState = { count: 0 }

    const reducer = (state, action) => {
      switch(action.type) {
        case 'INC':
            console.log(state)               <------- It is getting print twice
            return {
                count: state.count++
            }
        case 'DEC':
            console.log(state)
            return {
                count: state.count--
            }
        default:
            
            return {
                count: state.count
            }
    }
}

const [componentState, dispatch] = useReducer(reducer, initialState);

return (
    <>
        {componentState.count}
        <button onClick={() => dispatch({type: 'INC'})}>Increase</button>
        <button onClick={() => dispatch({type: 'DEC'})}>Decrease</button>
    </>
)
}

export default Counter;

enter image description here

reactjs react-hooks
1个回答
1
投票

这是由于严格模式,在index.js中尝试删除react严格模式。您将只获得一台控制台,

注意:这只会在生产中调用一次

© www.soinside.com 2019 - 2024. All rights reserved.