React 学习 笔记
redux 的使用// 1. 引入 reduxjs/toolkit// 2. 创建一个 公共的组件 作为项目的根 stora 使用import{configureStore}fromreduxjs/toolkitexportconststoreconfigureStore({reducer:{// 具体的 store 切片 例如:auth:authReducer}})// 3. 在最外层 包裹住所有组件的地方 为了防止路由中使用仓库内容 最好是将路由组件 BrowserRouter 也包含import{Provider}fromreact-reduxProvider store{store}/Provider// 4. 处理具体的碎片内容import{createSlice}fromreduxjs/tookitcosnt authSlicecreateSlice({initialState:{token:,asyncLogin:},// 初始化的值reducers:{setToken:(state,action){state.tokenaction.payload.token}},// 初始初始化对象中 任意一个字段内容的方法extraReducers:{},// 监听别处来的 action并决定当前 slice 怎么更新 state。 可以接收异步处理初始化对象中的值 也可以对同一个 dispatch 触发 还可以监听自己手动创建的action})// 这两行是 固定写法// 是为了使用的时候 dispatchexportconst{setToken}authSlice.actions// 为了绑定到 跟 storeexportdefaultauthSlice.reducer// 4. 在页面具体使用的时候import{useDispatch,useSelector}fromreact-reduximport{setToken}from/store/modules/auth// 直接使用内容consttokenuseSelector(statestate.auth.token)// 创建 触发器constdispatchuseDispatch()// 然后 通过触发器 调用dispatch(setToken({token:token}))// 在实际使用的时候 往往会将 useDispatch 和 useSelector 进行封装import{useDispatch,useSelector,type TypedUseSelectorHook}fromreact-reduximporttype{AppDispatch,RootState}from./indexexportconstuseAppDispatchuseDispatch.withTypesAppDispatch()exportconstuseAppSelector:TypedUseSelectorHookRootStateuseSelector// 其中的引用类型 RootState AppDispatch 是在从根 store 中暴露出来的类型exporttype RootStateReturnTypetypeofstore.getStateexporttype AppDispatchtypeofstore.dispatch// 封装后的使用和 直接使用 useDispath 和 useSelector 写法上没有区别 只是为了方便 ts 推断类型在redux中访问异步接口返回信息 要使用 reduxjs/toolkit 提供的 createAsyncChunkconstasyncChunkcreateAsyncChunk(模块名/动作名,async(){return接口api})// 返回的内容包含 pending(发起接口) fulfilled(接口返回成功) rejected(请求失败)// 在使用的时候 放在extraReducers中 通过参数 builder进行// extraReducers 是在 reduxjs/toolkit 提供的辅助当前 slice 响应非 reducers 定义的 actioncreateSlice({...,extraReducers:builder{builder.addCase(asyncChunk.pending,(state){}).addCase(asyncChunk.fulilled,(state,action){}).addCase(asyncChunk.rejected,(state){})}})// 在使用中awaitdispatch(fetchCurrentUser()).unwrap().catch(()null)// 因为是 通过createChunk创建的action碎片 所以要使用dispatch触发 然后使用 unwarp 是为了将返回结果解析成为 promise 形式 否则就是 { type: ..., payload:...}// 如果需要该动作不影响下一步的你处理 或者不被外层的 try/catch接住 那么就写 .catch 自己接住并处理错误 那么就不影响后续的操作 也可以使用 try/catch把这一段包裹路由 react-router-dom 的使用import{matchRoutes,Navigate,useLocation,useRoutes}fromreact-router-domconstroutes[{path:,element:,children:[{}]}]constRouter(){constelementuseRoutes(routes)return({element}/)}// 其中 element 可以是具体组件 也可以是重定向: Navigate to/login replace /// 类似于vue的路由拦截器 在 react 中是没有绑定的 需要自己重新添加一个 组件 在组件中进行处理 ps:自定义路由配置文件 然后通过中间处理的方式 根据配置生成真实的路由配置 然后在组件中传入配置项 router/meta// 访问子路由的时候 使用 Outlet 进行占位import{Outlet,useLocation,useNavigate}fromreact-router-domOutlet/// 使用 获取路由地址 参数 状态或者是跳转路由的时候 使用 useLocation, useNavigate hooksconstnavigateuseNavigate()constlocationuseLocation()