diff --git a/src/App.js b/src/App.js index f98d7cd..ae7d83a 100644 --- a/src/App.js +++ b/src/App.js @@ -10,9 +10,9 @@ import SonPage from "./pages/SonPage"; import Page3 from "./pages/Page3"; // import store from "./store/msgReducer"; -import {connect} from "react-redux" +import {connect, useDispatch, useSelector} from "react-redux" -import {changeMsg} from "./store/tookit"; +import {changeMsg, addCount, changeCountThunk} from "./store/tookit"; // 异步组件, 懒加载 const LazyPage = React.lazy(()=> import("./pages/SonPageLazy")) @@ -21,6 +21,23 @@ function App(props) { console.log("App props =>", props) // console.log("store", store, store.getState()) + // hook 用法 + const count = useSelector((state)=>{ + console.log("hook state =>", state) + return state.countReducer.count + }) + console.log("count =>", count) + const dispatch= useDispatch() + const addCountFn = useCallback(()=>{ + // dispatch({ + // type: "countSlice/addCount" + // }) + dispatch(addCount()) + }, [dispatch]) + const changeCountFn = useCallback(()=>{ + dispatch(changeCountThunk(count + 1)) + }, [count, dispatch]) + // vue3 组合式 API // React 必须大写 Pascal 命名 组件 function FnHello({name = "Fn"}) { @@ -307,10 +324,22 @@ function App(props) { Redux
- {props.msg} +
+ {props.msg} +
+
+ +
+
- +
+ Count State => {count} +
+
+ + +
@@ -322,7 +351,7 @@ function App(props) { // 第一个参数 映射 state, 把需要使用的 state 映射到组件的 props // 第二个参数 为方法映射, 往 props 传入哪些方法 export default connect((state) => { - console.log("connect state", state) + console.log("connect state", state) return { msg: state.msgReducer.msg } diff --git a/src/store/tookit.js b/src/store/tookit.js index f2f5701..939b138 100644 --- a/src/store/tookit.js +++ b/src/store/tookit.js @@ -1,4 +1,4 @@ -import {configureStore, createSlice} from "@reduxjs/toolkit"; +import {configureStore, createSlice, createAsyncThunk} from "@reduxjs/toolkit"; let msgSlice = createSlice({ name: "msgSlice", @@ -12,6 +12,18 @@ let msgSlice = createSlice({ } }) +// 第一个参数为名称 +// 第二个为异步方法 +export let changeCountThunk = createAsyncThunk("countSlice/changeCountThunk",async (params)=>{ + return await new Promise(resolve => { + console.log("changeCountThunk params", params) + + setTimeout(()=>{ + resolve(params) + },500) + }) +}) + let countSlice = createSlice({ name: "countSlice", initialState: { @@ -21,9 +33,27 @@ let countSlice = createSlice({ addCount(state, action){ state.count+=1 } + }, + extraReducers:(chunk)=>{ + chunk.addCase(changeCountThunk.pending, ()=>{ + console.log("changeCountThunk pending") + }).addCase(changeCountThunk.fulfilled, (state, action)=>{ + state.count = action.payload + }) } + // 废弃 + // extraReducers: { + // [changeCountThunk.pending]: ()=>{ + // console.log("changeCountThunk pending") + // }, + // [changeCountThunk.fulfilled]: (state, action)=>{ + // state.count = action.payload + // } + // } }) + + let store = configureStore({ reducer: { msgReducer: msgSlice.reducer,