React基础之useReducer
React基础之useReducer
useState适用于管理简单的状态逻辑,如单个状态值或少量不相关的值,useReducer适合管理复杂的状态逻辑
1.定义不懂的reducer函数,根据不同的action,返回不同的状态
2.组件中调用useReducer(reducer,0)=>[state,dispatch]
3.调用dispatch({type:‘INC’}),同时reducer产生一个新的状态,使用这个新状态更新UI
import
{
useReducer
}
from
“react”
;
function
reduce
(
state
,
action
){
switch
(
action
.
type
){
case
‘INC’
:
return
state
1
case
‘DEC’
:
return
state
1
default
:
return
state
}
}
function
App
() {
const
[
state
,
dispatch
] =
useReducer
(
reduce
,
0
)
return
(
<
div
className
=
“App”
this is app,
{
state
}
<
button
onClick
=
{
()
=>
{
dispatch
({
type:
‘INC’
})}
}
++
</
button
<
button
onClick
=
{
()
=>
{
dispatch
({
type:
‘DEC’
})}
}
–
</
button
</
div
);
}
export default
App
;
如果我们需要action传参
只需要添加一个新的分支,并且使用payload指定参数即可
import
{
useReducer
}
from
“react”
;
function
reduce
(
state
,
action
){
switch
(
action
.
type
){
case
‘SET’
:
return
action
.
payload
default
:
return
state
}
}
function
App
() {
const
[
state
,
dispatch
] =
useReducer
(
reduce
,
0
)
return
(
<
div
className
=
“App”
this is app,
{
state
}
<
button
onClick
=
{
()
=>
{
dispatch
({
type:
‘SET’
,
payload:
100
})}
}
更新
</
button
</
div
);
}
export default
App
;