-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
对应 commit 记录:bfc04d2570a9c7f83addc963a589e3a02efed24a
使用 git reset --hard bfc04d2 回退到此版本
一、src 目录下创建 stores 文件夹
- common.slice.ts
import { createSlice } from "@reduxjs/toolkit"
export const commonSlice = createSlice({
name: "common1",
initialState: {
count: 1,
},
reducers: {
increment(state) {
state.count += 1
},
decrement(state) {
state.count -= 1
}
}
})- stores.ts
import { configureStore } from '@reduxjs/toolkit'
import { commonSlice } from './common.slice'
const stores = configureStore({
reducer: {
common: commonSlice.reducer,
},
})
export default stores二、main.tsx 中引入 store
import { Provider } from 'react-redux'
import stores from './stores/stores'
const rootElement = document.getElementById('root')
const isStrictMode = true
if (rootElement) {
const WithStoreApp = () => <Provider store={stores}><App /></Provider>
const AppRender = isStrictMode
? (
<React.StrictMode>
<WithStoreApp />
</React.StrictMode>
)
: <WithStoreApp />
ReactDOM.createRoot(rootElement).render(AppRender)
} else {
console.error("root element not found")
}三、定义 store 类和带类型的工具方法
- @types/store.d.ts
interface ICommonSliceState {
count: number,
}
interface IStoreState {
common: ICommonSliceState,
}- hooks/store.hook.ts
import { TypedUseSelectorHook, useSelector } from "react-redux";
export const useTypedSelector: TypedUseSelectorHook<IStoreState> = useSelector;四、页面中使用
- pages/about/about.tsx
import { useDispatch } from "react-redux";
import { useTypedSelector } from "../../hooks/store.hook"
import { commonSlice } from "../../stores/common.slice";
const AboutPage = function () {
const count = useTypedSelector(state => state.common.count)
const dispatch = useDispatch();
const handleCommonIncrement = () => {
dispatch(commonSlice.actions.increment())
}
return (
<div>
<h3>this is AboutPage-{count}-{count2}</h3>
<button onClick={handleCommonIncrement}>redux-common-increment</button>
</div>
)
}
export default AboutPageReactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels