FE-Interview icon indicating copy to clipboard operation
FE-Interview copied to clipboard

多个组件之间如何拆分各自的 state,每块小的组件有自己的状态,它们之间还有一些公共的状态需要维护,这如何思考

Open lgwebdream opened this issue 5 years ago • 2 comments

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。

lgwebdream avatar Jul 06 '20 16:07 lgwebdream

  • 安装依赖@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

LoveWei0 avatar Jun 10 '23 02:06 LoveWei0