React项目报错Cannot read properties of undefined (reading 'toLowerCase')怎么解决?
解决React中"Cannot read properties of undefined (reading 'toLowerCase')"错误
错误原因分析
你的错误出在两个核心点:
- App.js定时器调用逻辑错误:
showAlert函数里的定时器调用了showAlert(null),但该函数需要接收message和type两个参数,仅传null会导致type参数为undefined,最终alert状态变为{msg: null, type: undefined}。Alert组件渲染时,props.alert.type是undefined,传给capitalize函数后调用toLowerCase()触发报错。 - 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
相关产品推荐
相关产品推荐

