React Native同组件内调用dispatch未触发AlertReducer不显示弹窗问题
问题原因
1. AlertChild组件参数接收错误
React函数组件的第一个参数是props对象,你当前的写法直接把整个props赋值给了visible变量,而非读取props上的visible属性。正确的解构写法应该是:
// 错误写法 const AlertChild = (visible = true) => {} // 正确写法 const AlertChild = ({ visible = true }) => {}
2. AlertChild的useEffect依赖项缺失
你通过useSelector订阅了store中的alert状态,但useEffect的依赖数组中没有加入alert变量。当alert状态更新时,useEffect不会重新执行,ShowAlert函数自然不会被触发,就算reducer正常更新了状态也不会弹出提示。
3. 若确认reducer完全未触发需额外排查
- 检查Login组件是否和其他能正常调用alert的组件一样,被同一个Redux Provider包裹,没有脱离Redux上下文,导致
useDispatch拿到的是无效的dispatch函数 - 检查Login组件中
AlertActions的导入路径是否正确,若导入路径错误会拿到错误的action生成函数,dispatch后reducer不会响应
修复方案
直接修改AlertChild组件的代码即可:
import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux"; import { Toast } from "native-base"; import { AlertActions } from "../Store/Actions/AlertActions"; // 1. 解构props获取visible属性 const AlertChild = ({ visible = true }) => { const alert = useSelector((state) => state.alert.alert); const dispatch = useDispatch(); // 2. 依赖项加入alert,状态变化时自动触发 useEffect(() => { ShowAlert(); }, [visible, dispatch, alert]); function ShowAlert() { if (visible && alert !== undefined && Object.keys(alert).length) { Toast.show({ text: alert.message, buttonText: "X", type: alert.type, duration: alert.type === "danger" ? 60000 : 6000, }); dispatch(AlertActions.clear()); } } return <></>; }; export default AlertChild;
内容的提问来源于stack exchange,提问作者Dr oscar
相关产品推荐
相关产品推荐

