类型错误:未定义不是对象(评估“this.setState”)

JJN*_*L77 6 javascript reactjs

我一直收到这个错误,我不知道为什么,因为我尝试过的一切都不起作用。有谁知道为什么这不起作用以及它如何工作?

我在这里未定义:

this.setState({isAuthenticated: true})
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

class Login extends Component{

        constructor(props){
            super(props);

            this.state ={
                email: '',
                password: '',
                isAuthenticated: false
            };

            function login(username, email){
                sessionStorage.setItem('loginSessionUsername', username);
                sessionStorage.setItem('loginSessionEmail', email);
                this.setState({isAuthenticated: true})
            }
        }

        render(){
            const isAuthenticated = this.state.isAuthenticated;
            if(isAuthenticated){
                return(
                    <div>
                        <Servicedesk />     
                    </div>
                )
            }
            return(
                <div id='Login' className='setVisible'>
                    <div>
                        <label>Emailadres</label>
                        <input type='text' placeholder='je email' onChange={ev => this.setState({email: ev.target.value})}/>
                        <label>Wachtwoord</label>
                        <input type='password' placeholder='je wachtwoord' onChange={ev => this.setState({password: ev.target.value})}/>
                        <br />
                        <button onClick={(event => this.handleClick(event))}>Submit</button>
                    </div>
                </div>
            )
        }
    }

    export default Login;
Run Code Online (Sandbox Code Playgroud)

Dra*_*ity 11

您应该使用箭头函数(参见文档),它将上下文绑定到您的函数,如下所示:

const login = ( username, email) => {
        sessionStorage.setItem('loginSessionUsername', username);
        sessionStorage.setItem('loginSessionEmail', email);
        this.setState({isAuthenticated: true})
    }
Run Code Online (Sandbox Code Playgroud)