redux-toolkit是redux的升级版
安装
npm install @reduxjs/toolkit
// 在react中还需要搭配react-redux使用
npm install react-redux
模块的写法
// counterReducer.ts
import { createSlice, payloadAction } from '@reduxjs/tookit'
export const counterSlice = createSlice({
name: 'counter',
initialState: {
num: 0
},
reducers: { // 类似vuex的commit;reducers,reducers,reducers,不是reducer
// 写法类似vuex的commit,第一个参数默认是state,第二个是自己传的参数,
// payloadAction是内置用于ts情况下类型校验的,把参数包裹起来
increment(state, value: payloadAction<number>) {
state.num += value
}
}
})
// 导出
export const { increment } = counterSlice.action
export default counterSlice.reducer
创建仓库
// stroe/index.ts
import { configureStore } from '@reduxjs/tookit'
// 创建仓库configureStore
const store = configureStore({
// 模块,类似vuex的module
reducer: {
counter: counterReducer
}
})
// 导出
export type RootState = ReturnType<typeof store.getState> // 这两个是为ts定义类型用的
export type AppDispatch = typeof store.dispatch
// 这个重要
export default store
通过react-redux在组件中使用redux
1. 首先要在react应用的根组件provider
// index.jsx
import store from './store'
import { Provider } from 'react-redux'
root.render(
<React.strictMode>
<Provider store={store}>
<App />
</Provider>
</React.strictMode>
)
2. 然后才能在组件中使用
// 这两个是react用个来使用/操作redux的
import { useSelector, useDispatc } from 'react-redux'
import { increment } from '@/store/couterReducer'
export default function App() {
const num = useSelector((state: RootState) => state.counter.num)
const dispatch = useDispatch()
return (
<>
<p>{num}</p>
<button onClick={() => {
dispatch(increment()) //这就是触发reducer更改store的方法
}}> increment </button>
</>
)
}
标签:基操,redux,const,Toolkit,react,export,import,Redux,store
From: https://www.cnblogs.com/Lilc20201212/p/16791544.html