【问题标题】:React typeerror in axios callback TypeError: this.setState is not a function在axios回调TypeError中反应typeerror:this.setState不是函数
【发布时间】:2020-03-28 10:50:42
【问题描述】:

我知道很多问题都与堆栈溢出有关,但我是新来的反应和堆栈溢出,我找不到任何解决方案所以,我被卡住了。所以每次我尝试实现这段代码时,我都会得到 TypeError: this.setState is not a function error 并且代码已经在 ES6 中。此行发生错误:this.setState({token : true});。我不知道如何在那里设置状态。我已将 loginSubmit 函数绑定到 this 但它仍然无法正常工作...


  import React from 'react';
import './Login.css';
import axios from 'axios';
import {Redirect} from 'react-router-dom';

class Login extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            username : '',
            password : '',
            token : false
        }
        this.onChangeHandler = this.onChangeHandler.bind(this);
        this.loginSubmit = this.loginSubmit.bind(this);
    }
    componentDidMount(){
        let token = localStorage.getItem('token');
        if(token!==null && token!==undefined){
            this.setState({token : true});
        }
    }
    onChangeHandler(event){
        this.setState({[event.target.id]:event.target.value});
        console.log(this.state.username,this.state.password);
    }
    loginSubmit(event){
        event.preventDefault();
        let loginFormData = new FormData();
        loginFormData = {
            'username' : this.state.username,
            'password' : this.state.password
        }
        axios({
            method : 'post',
            url : 'http://localhost:3001/loginApi',
            data : loginFormData
        })

        .then((response)=>{

            if(response.data.msg=="database error"){
                console.log("database error");
            }
            if(response.data.msg=="no user found username or password incorrect"){
                console.log("no user found username or password incorrect");
            }
            if(response.data.msg=="jwt error"){
                console.log("jwt error");
            }
            if(response.status==200 && response.data.result!=null && response.data.result!=undefined && response.data.token!=null && response.data.token!=undefined){
                console.log("user logged in && loginapi response.data.result:",response.data.result,response.data.token);
                localStorage.setItem('token',response.data.token);
                this.setState({token : true});
            }
        })
        .catch((response)=>{
            console.log("catch response api call fail:",response);
            localStorage.removeItem('token');
        });
        this.setState = {
            username : '',
            password : ''
        }
    }

    render(){
        if(this.state.token){
            return <Redirect to='/profile' />
        }
        return(
            <>
            <div className="all">
                <div className="sidenav">
                    <div className="login-main-text">
                        <h2>Application<br/> Login Page</h2>
                        <p>Login from here to access.</p>
                    </div>
                </div>
                <div className="main">
                    <div className="col-md-6 col-sm-12">
                        <div className="login-form">
                            <form>
                                <div className="form-group">
                                    <label>User Name</label>
                                    <input name="username" id="username" value={this.state.username} onChange={(event)=>this.onChangeHandler(event)} type="text" className="form-control" placeholder="User Name"/>
                                </div>
                                <div className="form-group">
                                    <label>Password</label>
                                    <input name="password" id="password" value={this.state.password} onChange={(event)=>this.onChangeHandler(event)} type="password" className="form-control" placeholder="Password"/>
                                </div>
                                <button name='logionSubmit' id='logionSubmit' onClick={(event)=>this.loginSubmit(event)} type="submit" className="btn btn-black">Login</button>
                            </form>
                        </div>
                    </div>
                </div>
                </div>
            </>
        );
    }
}

export default Login;

因此,自动重定向不起作用,我每次都必须刷新页面以重定向到配置文件。重定向代码如下。

   render(){
        if(this.state.token){
            return <Redirect to='/profile' />
        }
        return( and then some jsx code goes here);

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    更新:

    You are re-assigingthis.setState 当它需要被视为不可变时:

    this.setState = {
      username: "",
      password: "",
    };
    

    永远不要直接改变 this.state,因为之后调用 setState() 可能会替换你所做的改变。将 this.state 视为不可变的。

    然后在axios中异步调用this.setState


    没有可生产的例子,可能是因为you didn't bind loginSubmit to this instance.

    根据您使用的语法和构建步骤,有多种方法可以确保函数能够访问 this.propsthis.state 等组件属性。

    // Class Properties
    loginSubmit = (event) => {
      ...
    }
    

    或者在构造函数中绑定:

    // Bind in constructor
    constructor(props) {
      super(props)
      this.loginSubmit = this.loginSubmit.bind(this);
    }
    

    【讨论】:

    • 我像你说的那样绑定它,但它不起作用。对不起,我忘了说我是新手,所以希望你能理解
    • 你需要问一个完整的问题,请阅读如何:How to create a Minimal, Reproducible Example
    • 你为什么要给this.setState分配一些东西,试着删除它。
    • 对不起,我是新手,这次我放了整个代码并更新了它。
    • 我更新了答案...下次按预期发布一个最小示例
    【解决方案2】:

    很难从您的代码中分辨出来,因为您需要共享更多代码,这可能是因为您需要在类构造函数中调用super(props)

    【讨论】:

    • 对不起,我没有提到,但我已经这样做了,但仍然没有工作我已经用完整代码更新了代码,现在你可以查看它
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-09-16
    • 2017-09-11
    • 2018-01-22
    • 2018-06-05
    • 2020-06-11
    相关资源
    最近更新 更多