Javascript &引用;这";在react组件中未定义
我有以下组成部分:Javascript &引用;这";在react组件中未定义,javascript,reactjs,Javascript,Reactjs,我有以下组成部分: import React from 'react'; import {Route, Redirect} from 'react-router-dom'; import {isAuthenticated} from "../../helpers/auth_utils"; const PrivateRoute = ({component, ...rest}) => { //TODO how these two component's are different?
import React from 'react';
import {Route, Redirect} from 'react-router-dom';
import {isAuthenticated} from "../../helpers/auth_utils";
const PrivateRoute = ({component, ...rest}) => {
//TODO how these two component's are different?
let {component: Component, ...componentProps} = this.props;
return (<Route {...rest} render={props => {
if (isAuthenticated()) {
return <Component component={component} {...componentProps}/>;
} else {
return <Redirect to={{pathname: '/login', state: {from: props.location}}}/>;
}
}
}/>);
};
export default PrivateRoute;
从“React”导入React;
从“react router dom”导入{Route,Redirect};
从“./../helpers/auth_utils”导入{isAuthenticated}”;
常量privaterout=({component,…rest})=>{
//TODO这两个组件有何不同?
让{component:component,…componentProps}=this.props;
报税表({
如果(isAuthenticated()){
返回;
}否则{
返回;
}
}
}/>);
};
导出默认私有路由;
奇怪的是,
这个
在这个组件中没有定义。我做错了什么 箭头函数没有自己的此
。他们得到的范围在他们之上,这里的范围是窗口,但在严格模式下javascript不希望意外使用Window
,所以他们将其设为未定义。因此,此
未定义
您可以尝试将privaterout
包装到一个类中,您将看到this
就是这个类
要让函数创建自己的上下文,需要将其从箭头函数更改为常规函数
const privaterote=function({component,…rest}){
箭头函数没有自己的这个
。当您从这样一个函数引用这个
时,它是从外部的“正常”函数获取的
从
箭头函数表达式的语法比函数短
表达式,并且没有自己的this、arguments、super或
这些函数表达式最适合非方法
函数,它们不能用作构造函数
此
关键字不是指箭头函数,而是指常规函数
在你的情况下,你可以做这样的事情
const privaterote=(道具)=>{
//TODO这两个组件有何不同?
设{component:component,…componentProps}=props;
确保props中有
component
和componentProps
可用。您使用了arrow函数,它没有自己的独立作用域。在这种情况下,您应该在函数的参数中使用props,所以{…rest,component}是实数属性。
let user = {
firstName: "Arian",
sayHi() {
let arrow = () => alert(this.firstName);
arrow();
}
};
user.sayHi(); // Arian