首页 > 解决方案 > 在 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} />;

标签: javascriptreactjsreact-router

解决方案


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', '');

推荐阅读