简体   繁体   中英

React: TypeError: Cannot read property 'setState' of undefined

Im noob with React and trying to create a login form. When the user enters correct login informations a rest api will return JWT token. However i cant find how to set the state "token" to be the value of the response. Still i can save the response.token to localstorage and it shows correctly. I think the "this" points to wrong function, but how could i get around this without breaking the logic? Any hints? Thanks

Login.js

import React from 'react';

import axios from 'axios';

import Glyphicon from 'react-bootstrap/lib/Glyphicon';

import MyInput from './../components/Input';

import { connect } from "react-redux";

import { Form } from 'formsy-react';

var server = "http://localhost:3000";

class Login extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            canSubmit: false,
            token: null
        };
        this.enableButton = this.enableButton.bind(this);
        this.disableButton = this.disableButton.bind(this);
        this.submit = this.submit.bind(this);
    }

    submit(data) {
        axios.post(server + '/login', {
            username: data.username,
            password: data.password
        })
            .then(function (response) {
                if (response.data.token) {
                    var token = response.data.token;
                    localStorage.setItem("token", token);
                    this.setState({ token: token }); //Here is the problem
                    console.log(this.state.token);
                } else {
                    location.reload();
                }
            });
    }

    enableButton() {
        this.setState({ canSubmit: true })
    }
    disableButton() {
        this.setState({ canSubmit: false })
    }

    render() {
        return (
            <div className="loginForm">
                <h2 className="page-header">Login</h2>
                <Form onSubmit={this.submit} onValid={this.enableButton} onInvalid={this.disableButton}>
                    <div className="form-group">
                        <label>Username: </label>
                        <MyInput name="username" validations="isExisty" validationError="Required" required />
                    </div>
                    <div class="form-group">
                        <label>Password: </label>
                        <MyInput type="password" name="password" validations="isExisty" validationError="Required" required />
                    </div>
                    <button
                        type="submit"
                        className="btn btn-primary"
                        disabled={!this.state.canSubmit}>
                        Login
                    </button>
                </Form>
                <br/>
                <a href="register">Create user!</a>
                <a id="forgot" href="forgot">Forgot password?</a>

            </div>);
    }
}
export default Login;

You can use an arrow function to keep the context of submit and be able to access to setState :

submit(data) {
    axios.post(server + '/login', {
      username: data.username,
      password: data.password
    })
    .then((response) => {
        if (response.data.token) {
            var token = response.data.token;
            localStorage.setItem("token", token);
            this.setState({ token: token });
            console.log(this.state.token);
        } else {
            location.reload();
        }
    });
}

由于亚历山大的评论所说,我必须使用箭头功能=>或设置this回调。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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