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

React应用中Redux useSelector无法控制台打印habits状态问题

Redux useSelector获取habits数据失败,控制台无有效打印

我正在学习Redux,但浏览器控制台无法输出正确的habits数据,仅打印undefined。以下是相关代码片段,同时提供了在线沙箱用于调试:

import React from "react";
import { useSelector } from "react-redux";
import { RootState } from "../store/store";
import { Box } from "@mui/material";

const HabitList: React.FC = () => {
  const { habits } = useSelector((state: RootState) => {
    state.habits;
  });
  return <Box>{console.log("habits", habits)}</Box>;
};

export default HabitList;

问题原因

useSelector的回调函数未返回值:你使用带大括号的箭头函数时,仅在内部写了state.habits;语句,但没有显式返回该值,箭头函数默认返回undefined。这导致解构得到的habits为undefined,控制台自然无法输出有效数据。

修复方案

有两种简洁的修复方式:

方式1:显式返回state.habits

const { habits } = useSelector((state: RootState) => {
  return state.habits;
});

方式2:使用箭头函数简写(自动返回)

去掉大括号,箭头函数会自动返回表达式结果:

const { habits } = useSelector((state: RootState) => state.habits);

修复后的完整代码

import React from "react";
import { useSelector } from "react-redux";
import { RootState } from "../store/store";
import { Box } from "@mui/material";

const HabitList: React.FC = () => {
  const { habits } = useSelector((state: RootState) => state.habits);
  return <Box>{console.log("habits", habits)}</Box>;
};

export default HabitList;

修改后,useSelector就能正确从Redux Store中获取habits数据,控制台会打印出预期内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 16:41:10