为什么 useReducer hook 会重新渲染它的组件两次?
why useReducer hook re-render its component twice?
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 按钮时 (App 组件) 重新渲染并记录 'render string' 到控制台两次?
这是正常行为吗?
我认为它实际上并没有渲染两次,因为当它被放置在像
这样的 useEffect 中时
useEffect(()=> console.log("render") )
只调用一次,useEffect相当于componentDidMount
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 按钮时 (App 组件) 重新渲染并记录 'render string' 到控制台两次?
这是正常行为吗?
我认为它实际上并没有渲染两次,因为当它被放置在像
这样的 useEffect 中时useEffect(()=> console.log("render") )
只调用一次,useEffect相当于componentDidMount