简体   繁体   English

为什么会收到TypeError:this.getToken不是函数-React JS

[英]Why do I get a TypeError: this.getToken is not a function - React JS

I've created a login page that consumes a json API. 我创建了一个使用json API的登录页面。 The login page generates a token upon successful authentication and directs the user to a page that will consist of three dropdown boxes. 登录页面在成功通过身份验证后会生成一个令牌,并将用户定向到一个包含三个下拉框的页面。 In focusing on just one of the dropdown boxes, I'm attempting to have the dropdown box to display the client's user name according to their token. 在仅关注其中一个下拉框时,我尝试使该下拉框根据客户端的令牌显示客户端的用户名。

The login page calls a function from another react JS page that authenticates the user. 登录页面从另一个对用户进行身份验证的react JS页面调用一个函数。

The function: 功能:

getToken() {
        // Retrieves the user token from localStorage
        return localStorage.getItem('id_token')
    }

In my landing page, which contain the dropdown box, I have the following code: 在包含下拉框的登录页面中,我具有以下代码:

   componentDidMount() {
        fetch('http://theClientAPI:1111/api/clients', {
            method: 'GET',
            headers: {
                'Content-type': 'application/json',
                'Authorization': `Bearer ${this.getToken()}`
            },
        })
        .then(results => results.json())
        .then(data => this.setState({ data: data }))
    }

In the render() section, I have the following: 在render()部分,我具有以下内容:

 <div>
        <select className="custom-select" id="clientName">
                { this.state.data.map(item =>(
                <option key={item.clientName}>{item.clientName}</option>
                ))
                }
            </select>
        </div>

The error appears on this line of my Fetch: 错误出现在我的提取的这一行:

'Authorization': `Bearer ${this.getToken()}`

Could I get some assistance as to what I'm doing wrong? 关于我做错了什么,我可以得到一些帮助吗? Please let me know if you require more information. 如果您需要更多信息,请告诉我。 I posted the code behind my login and the authentication page below: 我将代码张贴在登录名和下面的身份验证页面的后面:

Login Page: https://codepen.io/lkennedy009/pen/GdYOYe?editors=0010#0 AuthService Page: https://codepen.io/lkennedy009/pen/xjyPMY 登录页面: https: //codepen.io/lkennedy009/pen/GdYOYe ? editors = 0010#0 AuthService页面: https ://codepen.io/lkennedy009/pen/xjyPMY

There are a few possible errors with your code. 您的代码可能存在一些错误。

  1. It is common good practice to bind your functions in the constructor and will save you any additional errors you might encounter 将函数绑定到构造函数中是一种常见的良好做法,可以节省您可能遇到的任何其他错误

     constructor(props) { super(props); // This binding is necessary to make `this` work in the callback this.getToken = this.getToken.bind(this); } 
  2. Instead of calling your function like this 而不是像这样调用您的函数

     'Authorization': `Bearer ${this.getToken()}` 

    Always try to define it in a constant, it can help with debugging and it is a good practice because functions can get complex and making smaller components / patterns is what makes React useful - so you should do that. 始终尝试在常量中定义它,它可以帮助调试,这是一个好习惯,因为函数会变得复杂,并且使较小的组件/模式成为React有用的原因-因此,您应该这样做。 So instead of the example above try something like this: 因此,请尝试以下操作,而不是上面的示例:

     const bearerToken = this.getToken(); //check if you even get what you expect console.log(bearerToken); ... 'Authorization': `Bearer ${bearerToken}` 
  3. Finally, these are the changes I would try to make your code work: 最后,这些是我将尝试使您的代码正常运行的更改:

     constructor(props) { super(props); this.getToken = this.getToken.bind(this); } componentDidMount() { const bearerToken = this.getToken(); fetch('http://theClientAPI:1111/api/clients', { method: 'GET', headers: { 'Content-type': 'application/json', 'Authorization': `Bearer ${bearerToken}` }, }) .then(results => results.json()) .then(data => this.setState({ data: data })) } getToken() { return localStorage.getItem('id_token'); } 

The reason I defined getToken after componentDidMount its because of AirBnB's ESlint rules for Javascript would throw a warning if it was defined above componentDidMount or other reserved React functions (lifecycles and others) 如果在componentDidMount或其他保留的React函数(生命周期等)之上定义了AirBnB针对Javascript的ESlint规则,则我在componentDidMount之后定义getToken的原因将引发警告

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

相关问题 错误:this.getToken不是函数 - Error: this.getToken is not a function FireBase + React: TypeError: user.getToken is not a function - FireBase + React: TypeError: user.getToken is not a function React JS为什么函数名称出现未定义的错误? - React JS Why do I get a not defined error for function name? 反应为什么我在调用作为参数传递的 function 时收到错误“Uncaught TypeError: createTask is not a function”? - REACT Why do I get the error "Uncaught TypeError: createTask is not a function" when calling a function passed as a parameter? 为什么我运行这个示例node.js代码的“TypeError:object is not function”? - Why do I get “TypeError: object is not a function” running this example node.js code? 类型错误:messaging.getToken 不是 function - TypeError: messaging.getToken is not a function 如何从 util.js 文件导入 getToken 函数而不会出错? - How do I import getToken function from util.js file without getting an error? 如何摆脱这个JS错误:TypeError:$(...)。validate不是一个函数 - How do I get rid of this JS error: TypeError: $(…).validate is not a function JWT的Firebase GetToken返回-如何获取设备令牌? - Firebase GetToken Returns at JWT - How do I get a device token? 当我将函数传递给React.js的子组件时,为什么会出现未捕获的TypeError? - Why am I getting an uncaught TypeError when I pass a function to a child component in React.js?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM