useReducer
可以做状态的一个转换
它接收两个参数,一个是参数的状态,一个参数是控制状态的
import React, { useReducer } from 'react';
function Example() {
const [count, dispatch] = useReducer((state, action) => {
switch(action) {
case "add":
return state + 1;
case "sub":
return state - 1;
default:
return state;
}
},0);
return (
<div>
<p>this is {count}</p>
<button onClick={() => dispatch("add")}>Increment</button>
<button onClick={() => dispatch("sub")}>Decrement</button>
</div>
)
}
export default Example;
网友评论