You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中Redux Toolkit获取API数据后Hook不更新问题

React Native Redux Toolkit数据更新后useState不更新的解决方案

问题核心

你的代码存在两个关键问题:

  • dispatch(calanderAction("170838"))是异步操作,调用后立刻执行setCalanderData(calanderHere)时,Redux内的数据还未完成更新,拿到的仍是旧值。
  • useEffect依赖calanderData,每次setCalanderData都会触发useEffect重新执行,进而再次调用set,形成无限循环。

解决方案

方案1:直接使用Redux中的数据(推荐)

既然已经用Redux管理全局状态,没必要再用本地useState同步,直接在组件中使用useSelector获取的calanderHere即可,减少状态冗余:

import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { useNavigation } from '@react-navigation/native';
import { Calendar } from 'react-native-calendars';

import colors from '../Styles/colors';
import MainHeader from '../Components/Header/MainHeader';


import { useDispatch, useSelector } from 'react-redux';
import { calanderAction } from "../Redux/Features/CalanderKit/CalanderKit";
import FlatListItem from '../Components/FlatList/FlatList';    

const Attendance = () => {
    const dispatch = useDispatch();
    // 直接取用Redux中的状态
    const calanderHere = useSelector((state) => state.calander);

    useEffect(() => {
        // 组件挂载时仅请求一次数据,依赖为空数组确保只执行一次
        dispatch(calanderAction("170838"));
    }, [dispatch]) // dispatch是稳定引用,可安全加入依赖

    // 后续渲染或逻辑处理直接使用calanderHere即可
    // 比如 console.log(calanderHere?.posts?.result?.attendance)

    return(
        <></>
    )
}

方案2:若需本地state同步Redux数据

如果有本地修改需求必须使用useState,可单独添加一个useEffect监听Redux数据变化,当Redux数据更新时再同步到本地state:

import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import { useNavigation } from '@react-navigation/native';
import { Calendar } from 'react-native-calendars';

import colors from '../Styles/colors';
import MainHeader from '../Components/Header/MainHeader';


import { useDispatch, useSelector } from 'react-redux';
import { calanderAction } from "../Redux/Features/CalanderKit/CalanderKit";
import FlatListItem from '../Components/FlatList/FlatList';    

const Attendance = () => {
    const dispatch = useDispatch();
    const calanderHere = useSelector((state) => state.calander);
    const [calanderData, setCalanderData] = useState([]);

    // 组件挂载时发起数据请求
    useEffect(() => {
        dispatch(calanderAction("170838"));
    }, [dispatch])

    // 监听Redux状态变化,同步到本地state
    useEffect(() => {
        // 增加非空判断,避免初始空值覆盖有效数据
        if (calanderHere?.posts?.result?.attendance) {
            setCalanderData(calanderHere);
        }
    }, [calanderHere]) // 依赖Redux状态,状态更新时触发同步

    return(
        <></>
    )
}

关键提示

  • 永远不要在调用异步dispatch后立刻同步state,Redux的状态更新是异步流程,即使使用Redux Toolkit的createAsyncThunk也不例外。
  • useEffect的依赖要精准,只加入会触发副作用的变量,避免不必要的重渲染和循环。

内容的提问来源于stack exchange,提问作者umair ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 21:25:18