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

Redux store数据正常但页面渲染报undefined错误 刷新必现如何解决

问题根源

  • 你在组件中自行维护的loading状态逻辑完全错误:getThread是异步请求action,dispatch(getThread())调用后不会等待接口返回就会立刻执行下一行的setLoading(false),此时Redux中threads.current还未被赋值,初始状态下为undefined,页面退出时执行clearThread也会将其设为null,loading提前结束后渲染直接访问thread.title就会触发报错。
  • 你的getThread action中try/catch代码块位置错误,axios请求写在了try块外面,接口报错时无法被捕获,会直接抛出异常。

修复方案

1. 修正组件渲染逻辑

不需要单独维护loading状态,直接通过thread是否存在来判断渲染逻辑即可,修改后组件代码如下:

import '../../styles/article.css';
import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getThread } from '../../store/actions/forum_actions';
import { clearThread } from '../../store/actions';
const Thread = (props) => {
  const threads = useSelector((state) => state.threads);
  const thread = threads?.current;
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getThread(props.match.params.id));
  }, [dispatch, props.match.params.id]);

  useEffect(() => {
    return () => {
      dispatch(clearThread());
    };
  }, [dispatch]);

  return (
    <>
      {!thread ? (
        <p>Loading</p>
      ) : (
        <p>{thread.title}</p>
      )}
    </>
  );
};

export default Thread;

如果你要保留loading状态,也可以等异步请求完成后再修改loading,需要调整action的返回逻辑,或者在组件监听thread的变化来修改loading。

2. 修正action的异常捕获逻辑

把axios请求放到try块内部,避免接口报错无法捕获:

export const getThread = (id) => {
  return async (dispatch) => {
    try {
      const request = await axios.get(`/forum/thread/${id}`);
      dispatch(threads.getThread(request.data));
    } catch (error) {
      dispatch(threads.errorGlobal('Error retrieving thread'));
    }
  };
};

内容的提问来源于stack exchange,提问作者Cam Baker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:57:03