瀏覽代碼

fix:react

郑柏铃 4 天之前
父節點
當前提交
6eb156ef17

二進制
20.react/高阶/ReduxAsyncDataFlowDiagram-d97ff38a0f4da0f327163170ccc13e80.gif


+ 13 - 1
20.react/高阶/my-redux/src/pages/My.jsx

@@ -1,8 +1,16 @@
 import { useSelector,useDispatch } from "react-redux";
-import {setName} from '../store/slice/user';
+import {setName,setAge,asyncSetAge} from '../store/slice/user';
+import { useState } from "react";
 function My() {
     // useSelector 获取状态中所有的字段 但需要将具体的字段解析
     const userMsg = useSelector(({user2}) => user2)
+    // useDispatch 用于触发方法
+    /**
+     * 当事件初发时 会执行dispatch函数,传入了一个action对象,
+     * 此时,redux开始工作,会根据action.type属性找到正确的reducer函数
+     * 去修改状态
+     */
+    const [age,changeAge] = useState('');
     const dispatch = useDispatch()
     console.log(userMsg)
     return (
@@ -11,9 +19,13 @@ function My() {
             <p>
                 我叫{userMsg.name},今年{userMsg.age}岁,我家住在{userMsg.address}
             </p>
+            <input type="text" placeholder="请输入添加的年龄" onChange={(e)=> changeAge(e.target.value)} />
             <button onClick={()=>{
                 dispatch(setName('蜡笔小新'))
             }}>修改名字</button>
+            <button onClick={()=>{
+                dispatch(asyncSetAge(Number(age)))
+            }}>修改年龄</button>
         </div>
     )
 }

+ 36 - 1
20.react/高阶/my-redux/src/store/slice/user.js

@@ -15,6 +15,9 @@ const userSlice = createSlice({
             // console.log(state,action)
             // state.name = action.payload;
             state.name = payload;
+        },
+        setAge(state,{payload}) {
+            state.age+=payload
         }
     }
 })
@@ -23,4 +26,36 @@ export default userSlice.reducer;
 
 // 在slice对象中 有一个actions属性 类型是对象 
 // 存储所有reducer函数中的对象构建的方法
-export const {setName} = userSlice.actions;
+export const {setName,setAge} = userSlice.actions;
+
+
+/**
+ * Redux原生不支持一步处理机制 
+ * 需要通过一些中间件去完成
+ * RTK中内置了Thunk中间件可以完成一步任务处理
+ * 在UI组件调用dispatch时,可以传入一个Action对象,
+ * 还可以传入一个thunk函数
+ * 继而处理异步任务,处理后 在通过dispatch中的action去修改状态
+ * 
+ * 
+ * 什么是Thunk函数?
+ * 1.可以是普通函数,也可以是async函数
+ * 2.函数会接受两个参数:dispatch 和 getStaåååe 函数
+ * 3.dispatch:用来异步处理后,执行状态修改
+ * 4.getState:获取完整的store中的状态对象
+ */
+
+// export function asyncSetAge(age) {
+//   return (dispatch,getState) => {
+//     setTimeout(()=>{
+//         dispatch(setAge(age))
+//     },2000)
+//   }
+// }
+
+
+export const asyncSetAge = (age) => (dispatch,getState) => {
+    setTimeout(()=>{
+        dispatch(setAge(age))
+    },3000)
+}