简体   繁体   English

在React组件中未定义“ this”

[英]“this” is undefined inside a react component

I have the following component: 我有以下组成部分:

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;

It's strange that this is undefined in this component. 这是奇怪的是, this是在这个组件不确定的。 What am I doing wrong here? 我在这里做错了什么?

Arrow functinos don't have their own this . 箭箭功能者自己没有this They get the scope that's above them, here the scope is Window, but in strict mode javascript doesn't want accidental use of window , so they make it undefined. 他们得到了位于其上方的范围,这里的范围是Window,但是在严格模式下,javascript不想意外使用window ,因此将它们设为undefined。 Thus this is undefined. 因此, this是不确定的。

You can try wrapping PrivateRoute into a class, and you will see that then this would be the class. 您可以尝试将PrivateRoute包装到一个类中,然后您会看到this就是该类。

To have your function create it's own context, you need to change it from arrow function to regular one. 要让函数创建自己的上下文,您需要将其从箭头函数更改为常规函数。

const PrivateRoute = function({component, ...rest}) {

Arrow functions don't have their “own” this . 箭函数没有“自己” this When you reference this from such a function, it's taken from the outer “normal” function. 当您从此类函数中引用this函数时,它是从外部“正常”函数中获取的。

From MDN , MDN

An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target. 箭头函数表达式的语法比函数表达式短,并且没有自己的this,arguments,super或new.target。 These function expressions are best suited for non-method functions, and they cannot be used as constructors. 这些函数表达式最适合于非方法函数,因此不能用作构造函数。

let user = {
  firstName: "Arian",
  sayHi() {
    let arrow = () => alert(this.firstName);
    arrow();
  }
};

user.sayHi(); // Arian

this keyword does not refers to arrow function. this关键字不涉及箭头功能。 It refers to regular function. 它是指常规功能。

In your case, you can do some thing like this 就您而言,您可以做这样的事情

const PrivateRoute = (props) => { //TODO how these two component's are different? let {component: Component, ...componentProps} = props;

Make sure component and componentProps are available in props. 确保props中可以使用componentcomponentProps

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM