FE-Interview
FE-Interview copied to clipboard
多个组件之间如何拆分各自的 state,每块小的组件有自己的状态,它们之间还有一些公共的状态需要维护,这如何思考
扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。
- 安装依赖@reduxjs-toolkit
- 新建app文件夹
// store.js
import { configureStore } from '@reduxjs/toolkit';
import userSlice from './slice/userSlice'
export default configureStore({
reducer: {
count: countSlice,
user: userSlice
},
});
// 其他slice(每一个slice都是一个小的仓库)
import { createSlice } from '@reduxjs/toolkit'
const initialState = {
profile: {
name: '',
age: 0,
email: '',
login:false
}
}
const userSlice = createSlice({
name: 'user',
initialState,
reducers: {
setLogin (state, action) {
console.log(action)
const {name,age,email } = action.payload
state.profile = {
name,
age,
email,
login:true
}
},
setLogout (state, action) {
state.profile = initialState
}
}
})
export const { setLogin, setLogout } = userSlice.actions
export default userSlice.reducer
- 用hooks(useSelector)获取state
- 用hooks(useDispatch)派发action