## 核心代码, 业务简单, 数量少可以直接都写在一个文件
```
import { createSlice } from "@reduxjs/toolkit";
export const userSlice = createSlice({
name: "user",
initialState: {
token: ""
},
reducers: {
setToken: (state, action) => {
state.token = action.payload;
// 可以 localStorage 存一份进行持久化, vuex 的时候记得是有工具
window.localStorage.setItem("token", action.payload);
}
}
})
export const { setToken } = userSlice.actions
export const token = (state: any) => state.user.token || window.localStorage.getItem("token");
export default userSlice.reducer;
```
## 使用
```
setToken 和 token 根据自己的文件路径去导入
import { useSelector, useDispatch } from 'react-redux';
const dispatch = useDispatch()
const _token = useSelector(token)
// 设置需要使用 dispatch
dispatch(setToken(""))
```