安装
shell
npm install @reduxjs/toolkit react-redux
创建 store
src\store\index.js
js
import { configureStore } from '@reduxjs/toolkit';
import homeReducer from './modules/home';
const store = configureStore({
reducer: {
home: homeReducer,
},
});
export default store;
创建 Reducer
src\store\modules\home.js
js
import { getHomeGoodPriceData } from '@/services'
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
// 定义异步操作,用于获取首页商品价格信息
export const fetchHomeDataAction = createAsyncThunk('fetchdata', async (payload) => {
const res = await getHomeGoodPriceData()
return res
})
// 创建 Redux slice,管理首页相关的状态
const homeSlice = createSlice({
name: 'home',
// 定义初始状态,包含商品价格信息
initialState: {
goodPriceInfo: {},
},
// reducers 里面包裹的是同步的方法
reducers: {
// 定义 reducer,用于更新商品价格信息
changeGoodPriceInfoAction(state, { payload }) {
state.goodPriceInfo = payload
},
},
// 处理异步操作结果,更新状态
// 我们在extraReducers中放入的是异步的方法,我们在action中声明的方法可以在此处使用
// 在此处我们可以监听创建好的异步action,此处有三个取值是比较常用的
// 1、fulfilled 成功之后需要做的操作
// 2、pending 加载时需要做的操作
// 3、rejected失败后需要做什么处理
extraReducers: (builder) => {
builder.addCase(fetchHomeDataAction.fulfilled, (state, { payload }) => {
state.goodPriceInfo = payload
})
},
})
// 导出 reducer,供 Redux store 使用
export const { changeGoodPriceInfoAction } = homeSlice.actions
export default homeSlice.reducer
对以上builder的解释:此重载接受一个回调函数,该函数接收一个builder对象作为其参数。该构建器提供addCase,addMatcher和addDefaultCase函数,可以调用这些函数来定义此 reducer 将处理的操作。(详情建议官网查)
注入 store
src\index.js
Provider
是React Redux中非常重要的组件,它的主要作用是向整个React应用程序树提供Redux.store。
import { Provider } from 'react-redux'
js
import React, { Suspense } from 'react'
import ReactDOM from 'react-dom/client'
import { HashRouter } from 'react-router-dom'
import { Provider } from 'react-redux'
import { ThemeProvider } from 'styled-components'
import App from '@/App'
import './assets/css/index.less'
import 'normalize.css'
import store from './store'
import theme from './assets/theme'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<Suspense fallback='loading'>
<Provider store={store}>
<ThemeProvider theme={theme}>
<HashRouter>
<App />
</HashRouter>
</ThemeProvider>
</Provider>
</Suspense>,
)
使用 store
js
import React, { memo, useEffect } from 'react'
import { shallowEqual, useDispatch, useSelector } from 'react-redux'
import { fetchHomeDataAction } from '@/store/modules/home'
import { HomeWrapper } from './style'
import HomeBanner from './components/home-banner'
import SectionHeader from '@/components/section-header'
import SectionRooms from '@/components/section-rooms'
const Home = memo(() => {
/** 从redux中获取数据 */
const { goodPriceInfo } = useSelector(
(state) => ({
goodPriceInfo: state.home.goodPriceInfo,
}),
shallowEqual,
)
/** 派发异步的事件: 发送网络请求 */
const dispatch = useDispatch()
useEffect(() => {
dispatch(fetchHomeDataAction('xxxx'))
}, [dispatch])
return (
<HomeWrapper>
<HomeBanner />
<div className='content'>
<div className='good-price'>
<SectionHeader title={goodPriceInfo.title} />
<SectionRooms roomList={goodPriceInfo.list} />
</div>
</div>
</HomeWrapper>
)
})
export default Home