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

React中useState(null)触发Cannot read properties of null报错求助

问题解决办法

错误原因

  1. 初始状态alert为null,但Alert组件直接尝试读取props.alert.type,当alert是null时自然会触发"无法读取null的type属性"的错误。
  2. Alert组件里的条件渲染写法错误,没有用React的JSX语法包裹判断逻辑;另外App.js里设置的alert属性是message,但Alert.js里写成了msg,属性名不匹配。

修复步骤

修改Alert.js,做以下调整:

  • 先判断props.alert是否存在,不存在则不渲染整个alert容器
  • 修正属性名,把props.alert.msg改为props.alert.message
  • 正确使用条件渲染语法,同时可以根据alert.type设置对应的alert样式类

修改后的Alert.js代码:

import React from 'react'

function Alert(props) {
    // 当alert为null时,返回null不渲染任何内容
    if (!props.alert) return null;
    
    return (
        <div>
             <div className={`alert alert-${props.alert.type} alert-dismissible fade show`} role="alert">
                 <strong>{props.alert.type}</strong>: {props.alert.message}
                <button type="button" className="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
        </div>
    )
}

export default Alert

额外优化(可选)

你App.js里的toggleMode函数有个小问题:切换到light模式时提示的是"Dark mode has been enabled",反过来也是,提示文字搞反了,修正后更合理:

const toggleMode = () => {
  if (mode === 'dark') {
    document.body.style.backgroundColor = '#fff';
    showAlert("Light mode has been enabled", "success");
    setMode('light');
  } else {
    document.body.style.backgroundColor = '#06213d';
    showAlert("Dark mode has been enabled", "success");
    setMode('dark')
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 21:25:32