为什么用useReducer钩子将其组件重新渲染两次?

时间:2020-06-29 20:29:41

标签: javascript reactjs facebook react-hooks

import React, { useReducer } from 'react'

const reducer = (state, action) => {
  console.log(action.type);

  switch (action.type) {
    case 'inc': return state + 1
    default: return state
  }
}

function App() {
  const [counter, dispatch] = useReducer(reducer, 0)

  const countUp = () => (
    dispatch({ type: 'inc' })
  )

  console.log('render');

  return (
    <div>
      <h2>{counter}</h2>
      <button onClick={countUp}>Count up</button>
    </div>
  )
}

export default App

为什么当我单击“计数向上”按钮(应用程序组件)重新渲染并将两次“渲染字符串”登录到控制台时?

这是正常行为吗?

1 个答案:

答案 0 :(得分:0)

自从放置在诸如useEffect之类的东西中以来,我认为它实际上不会渲染两次

useEffect(()=> console.log("render") )

它只被调用一次,并且useEffect相当于componentDidMount。