gpt4 book ai didi

javascript - react : TypeError: Cannot read property 'setState' of undefined

转载 作者:数据小太阳 更新时间:2023-10-29 05:46:21 25 4
gpt4 key购买 nike

我是 React 新手,正在尝试创建一个登录表单。当用户输入正确的登录信息时,rest api 将返回 JWT token 。但是我找不到如何将状态“ token ”设置为响应的值。我仍然可以将 response.token 保存到 localstorage 并正确显示。我认为“this”指向错误的功能,但我怎么能在不破坏逻辑的情况下解决这个问题呢?有什么提示吗?谢谢

登录.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;

最佳答案

您可以使用箭头函数来保持 submit 的上下文并能够访问 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();
}
});
}

关于javascript - react : TypeError: Cannot read property 'setState' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39138974/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com