【问题标题】:why useReducer hook re-render its component twice? [duplicate]为什么 useReducer 钩子重新渲染它的组件两次? [复制]
【发布时间】:2020-10-20 02:14:29
【问题描述】:
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

为什么当我点击 Count up 按钮 (应用程序组件) 时会重新渲染并将“渲染字符串”记录到控制台两次?

这是正常行为吗?

【问题讨论】:

    标签: javascript reactjs facebook react-hooks


    【解决方案1】:

    我认为它实际上不会渲染两次,因为当放置在 useEffect 中时

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

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

    【讨论】:

    • 是的,useEffect 没有问题,但是我发现当我在 index.js 文件中使用 React.StrictMode 组件时,默认使用 create-react-app 它是在我重新渲染时重新渲染在类组件中使用 useState、useMemo、useReducer、shouldComponentUpdate、setState |我在这里找到了答案 =>> stackoverflow.com/questions/61578158/…
    猜你喜欢
    • 2020-03-17
    • 1970-01-01
    • 2020-05-17
    • 2020-07-09
    • 2020-07-11
    • 2020-03-14
    • 2020-09-07
    • 2022-10-02
    相关资源
    最近更新 更多