React中useState(null)触发Cannot read properties of null报错求助
问题解决办法
错误原因
- 初始状态
alert为null,但Alert组件直接尝试读取props.alert.type,当alert是null时自然会触发"无法读取null的type属性"的错误。 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">×</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
相关产品推荐
相关产品推荐

