当我重定向到登录组件时,我正在传递一条消息,然后该消息将作为 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/