前提條件
在React中使用Redux,官方要求安裝兩個插件,Redux Toolkit 和 react-redux
Redux Toolkit(RTK): 官方推薦編寫Redux邏輯的方式,是一套工具的集合集,簡化書寫方式
。
- 簡化 store 的配置方式
- 內(nèi)置 immer 支持可變式狀態(tài)修改
- 內(nèi)置 thunk 更好的異步創(chuàng)建
react-redux:用來鏈接 Redux 和 React組件
的中間件。
安裝
npm i @reduxjs/toolkit react-redux
瀏覽器插件 - Redux DevTools(推薦但不強(qiáng)制使用)
下載并啟用插件
控制臺找到redux選項
配置
目錄結(jié)構(gòu)
src 下創(chuàng)建 store,其中 index.ts/index.js 作為modules中所有store的集合
store/index.ts配置
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({
reducer: {},
})
// 后續(xù)使用useSelector時參數(shù)state的類型
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
export default store
index.ts 或 main.ts中注冊store
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
// 添加如下
import store from './app/store'
import { Provider } from 'react-redux'
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
至此已經(jīng)全局注冊了Redux
配置
這里以計數(shù)器為例,在store/modules中創(chuàng)建counterSlice.js/ts
同步配置
import { createSlice } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
export interface CounterState {
value: number
}
const initialState: CounterState = {
value: 0,
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
reducers: {
increment: (state:CounterState) => {
state.value += 1
},
decrement: (state:CounterState) => {
state.value -= 1
},
},
})
export default counterSlice.reducer
異步配置
import { createSlice,createAsyncThunk } from '@reduxjs/toolkit'
import type { PayloadAction } from '@reduxjs/toolkit'
export interface CounterState {
value: number
}
const initialState: CounterState = {
value: 0,
}
export const counterSlice = createSlice({
name: 'counter',
initialState,
// 同步操作
reducers: {
......
},
// 異步操作
extraReducers(builder){
// 這里的payload就是incrementAsync的返回值
builder.addCase(incrementAsync.fulfilled,(state,{payload})=>{
state.value += payload
})
}
})
// 定義異步函數(shù)
export const incrementAsync = createAsyncThunk<number>(
"incrementAsync",
async(p:number)=>{
const res = await new Promise<number>(r=>{
setTimeout(() => {
r(p)
}, 1000);
})
return res
})
export default counterSlice.reducer
store/index.ts 中注冊
import { configureStore } from "@reduxjs/toolkit";
// 引入counterSlice.ts
import counterStore from "./modules/counterSlice";
const store = configureStore({
reducer:{
// 注冊,注意名字要與counterSlice.ts中的name一致
counter:counterStore
}
})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch
export default store
再次查看Redux Tools工具,已經(jīng)發(fā)現(xiàn)value文章來源:http://www.zghlxwxcb.cn/news/detail-814947.html
使用
// useSelect用于選擇操作哪個store
// useDispatch用于生成實例,該實例可以調(diào)用reducers的function
import { useSelector, useDispatch } from "react-redux"
// 引入index中的RootState類型 js項目不需要
import { AppDispatch, RootState } from "@/store"
// 引入functions
import { decrement, increment, incrementAsync } from "@/store/modules/counterSlice"
const Demo = () => {
const count = useSelector((state: RootState) => state.counter.value)
const dispatch: AppDispatch = useDispatch() // 異步函數(shù)必須加AppDispatch類型,否則報錯,同步可以不添加
return (
<>
<div className="navbar_top"></div>
<div>{count}</div>
<button onClick={() => dispatch(increment({ value: 2 }))}>+2</button>
<button onClick={() => dispatch(incrementAsync(2))}>+2</button>
<button onClick={() => dispatch(decrement())}>-1</button>
</>
)
}
export default Demo
操作后通過工具發(fā)現(xiàn)value已經(jīng)改變文章來源地址http://www.zghlxwxcb.cn/news/detail-814947.html
到了這里,關(guān)于【React】TS項目配置Redux的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!