// 声明对象类型状态
import { useState } from "react";
function App() {
const [count, setCount] = useState({
count1: 0,
count2: 0,
});
return (
<div className="App">
<button
type="button"
onClick={() =>
setCount((x) => {
return {
...x,
count1: x.count1 + 1,
};
})
}
>
count is: {count.count1}
count is: {count.count2}
</button>
</div>
);
}
export default App;
// 多次声明
const [count1, setCount1] = useState(0)
const [count2, setCount2] = useState(0)
可以发现,相比于对象类型状态 ,多次声明状态的方式更加方便,主要是因为更新函数采用的是替换的方式而不是合并。
不过如果要在函数组件中处理多层数据嵌套逻辑,使用useState就显得力不从心了。好在开发者可以使用useReducer来处理此类问题:
import { useReducer } from "react";
function App() {
function reducer(state, action) {
switch (action.type) {
case "increment1":
return { ...state, count1: state.count1 + 1 };
case "increment2":
return { ...state, count2: state.count2 + 1 };
default:
throw new Error();
}
}
const [state, dispatch] = useReducer(reducer, {
count1: 0,
count2: 0,
});
return (
<>
<button onClick={() => dispatch({ type: "increment1" })}>
count1: {state.count1}
</button>
<button onClick={() => dispatch({ type: "increment2" })}>
count2: {state.count2}
</button>
</>
);
}
export default App;