javascript - 在 props 上使用 typeof 会导致 TypeError
问题描述
当我重定向到登录组件时,我正在传递一条消息,然后将其作为道具传递给 Loginform
登录.js
class Login extends React.Component {
constructor(props) { super(props);}
render() {
let msg = "";
console.log(typeof this.props.location.state); // Always exists
console.log(typeof this.props.location.state.redirectmsg); // results in typeError
if(typeof this.props.location.state.redirectmsg!=='undefined') { // results in TypeError
msg=this.props.location.state.redirectmsg;
}
return <Loginform msg={msg} />;
}
}
重定向
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={props => (false === true ? <Component {...props} /> : <Redirect to={{ pathname: "/login", state: { redirectmsg: "Kindly login first"} }} />)} />);
但是当我尝试检查它是否未定义时,它会给我错误。即使 console.log 也会给我错误。
答:由于状态键本身一开始是未定义的
let msg = ((this.props.location || {}).state || {}).redirectmsg || "";
return <Loginform msg={msg} />;
解决方案
this.props.location.state 正在控制台中记录一个值,因为它引用了最新值,所以一开始它是“未定义”,然后用另一个值更新。
尝试更换
console.log(typeof this.props.location.state);
和
console.log(typeof this.props.location.state + '');
并检查它是否未定义(我想这次它会是未定义的)。
将其转换为字符串会破坏引用,您会看到它是未定义的(this.props.location.state 的类型的第一个值)。
那时您正在调用 this.props.location.state.redirectmsg ,这将产生类型错误,因为 this.props.location.state 未定义。
对于这种验证,我建议您使用 lodash 或下划线 _.get(使用该 get,您可以检查深层属性并在某些属性未定义时使用默认值)。
使用 lodash get 的示例:
let msg = _.get(this, 'props.location.state.redirectmsg', '');
推荐阅读
- javascript - request.onprogress 没有做任何事情
- model-view-controller - MVC 5 - 从视图中向@User 添加方法
- r - 在 R 中读取文本文件中的分组
- sas - SAS:如何在程序退出时或通过宏删除查询输出文件(.sasbdat7 和 .log)?
- c++ - 在头文件的B类中调用方法A?
- android - Mediapipe 样本与最新版本的“androidx.camera”不兼容
- postgresql - 类型ORM外键
- elasticsearch - Logstash、Filebeat、ELK 堆栈
- javascript - 无法多次按下重置按钮
- c# - 有没有更好的方法来减少 if 语句