javascript - 在 props 上使用 typeof 会导致 TypeError

标签 javascript reactjs react-router

当我重定向到登录组件时,我正在传递一条消息,然后该消息将作为 prop 传递给 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 - 在 props 上使用 typeof 会导致 TypeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51297310/

相关文章:

javascript - div 显然无缘无故被压低

javascript - Discord.js 发送表情符号

javascript - JavaScript 中的关系比较

javascript - webpack 路径浏览器 polyfill 失败

javascript - 有没有办法使用样式化的组件有条件地更改组件的类型?

javascript - 将数组上解析的字符串存储到另一个数组

javascript - 使用 getUserMedia 访问音频输入

reactjs - 在 React Router 中使用参数重定向到父路由

reactjs - 如何从 Router 组件以外的组件访问路由参数

reactjs - react 路由器总是呈现 '/' 路径