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

React项目报错Cannot read properties of undefined (reading 'toLowerCase')怎么解决?

解决React中"Cannot read properties of undefined (reading 'toLowerCase')"错误

错误原因分析

你的错误出在两个核心点:

  1. App.js定时器调用逻辑错误:showAlert函数里的定时器调用了showAlert(null),但该函数需要接收message和type两个参数,仅传null会导致type参数为undefined,最终alert状态变为{msg: null, type: undefined}。Alert组件渲染时,props.alert.type是undefined,传给capitalize函数后调用toLowerCase()触发报错。
  2. Alert组件未做空值校验:capitalize函数直接对传入的word调用toLowerCase(),未处理word为undefined或null的情况,一旦参数异常就会抛出类型错误。

修复方案

1. 修正App.js的定时器逻辑

将定时器内的showAlert(null)改为直接调用setAlert(null),直接清空alert状态,避免传递错误参数:

const showAlert = (message, type) => {
  setAlert({
    msg: message,
    type: type,
  });
  setTimeout(() => {
    setAlert(null); // 替换原showAlert(null)
  }, 1000);
};

2. 给Alert组件的capitalize函数添加空值保护

在调用toLowerCase()前先检查参数是否有效,避免空值调用:

const capitalize = (word) => {
  if (!word) return ''; // 处理word为undefined或null的情况
  const lower = word.toLowerCase();
  return lower.charAt(0).toUpperCase() + lower.slice(1);
};

可选优化:给showAlert设置参数默认值

为避免后续调用时漏传参数导致问题,可给函数参数添加默认值:

const showAlert = (message = '', type = 'info') => {
  setAlert({
    msg: message,
    type: type,
  });
  setTimeout(() => {
    setAlert(null);
  }, 1000);
};

修复后的完整代码

修正后的App.js

import "./App.css";
import Navbar from "./Components/Navbar";
import TextForm from "./TextForm";
import React, { useState } from "react";
import Alert from "./Components/Alert";

function App() {
  const [mode, setMode] = useState("light");
  const [alert, setAlert] = useState(null);

  const showAlert = (message, type) => {
    setAlert({
      msg: message,
      type: type,
    });
    setTimeout(() => {
      setAlert(null);
    }, 1000);
  };

  const toggleMode = () => {
    if (mode === "light") {
      setMode("dark");
      document.body.style.backgroundColor = "black";
      showAlert("The dark mode has been set", "success");
    } else {
      setMode("light");
      document.body.style.backgroundColor = "white";
      showAlert("The light mode has been set", "success");
    }
  };
  return (
    <>
      <Navbar toggleMode={toggleMode} mode={mode} />
      <Alert alert={alert} />
      <TextForm
        heading="This is textarea"
        mode={mode}
        alert={alert}
        showAlert={showAlert}
      />
    </>
  );
}

export default App;

修正后的Alert.js

import React from "react";

export default function Alert(props) {
  const capitalize = (word) => {
    if (!word) return '';
    const lower = word.toLowerCase();
    return lower.charAt(0).toUpperCase() + lower.slice(1);
  };
  return (
    props.alert && (
      <div
        class={`alert alert-${props.alert.type} alert-dismissible fade show`}
        role="alert"
      >
        <strong>{capitalize(props.alert.type)}</strong>:{props.alert.msg}
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="alert"
          aria-label="Close"
        ></button>
      </div>
    )
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:53:10