重新渲染Reactjs之后,父组件立即失去状态

问题描述

我是React的新手,我试图编写一个在启动时会自动显示登录页面的应用程序,并且当用户成功登录父组件时,它会更新其状态以呈现仪表板组件而不是登录。

我发现的是,当用户登录时,它会正确更新父组件的状态并显示Dashboard组件一秒钟,但随后其状态再次更改并重新呈现Login组件。我认为是某种原因导致状态重置,但是我不确定是什么原因。

User.js:

class User extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',isLoggedIn: false
        }

        this.updateUser = this.updateUser.bind(this);
    }

    updateUser(newEmail) {
        console.log(`Entered User.updateUser,email: ${newEmail}`);
        this.setState({
            email: newEmail,isLoggedIn: false
        });
    }

    render() {
        if (this.state.isLoggedIn) {
            return <Dashboard/>
        }

        return <Login updateTheUser={this.updateUser}/>
    }
}

export default User;

Login.js:

class Login extends Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',password: '',};

        this.handleEmailChange = this.handleEmailChange.bind(this);
        this.handlePasswordChange = this.handlePasswordChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.handleResponse = this.handleResponse.bind(this);
    }

    handleEmailChange(event) {
        this.setState({email: event.target.value})
    }

    handlePasswordChange(event) {
        this.setState({password: event.target.value})
    }

    handleResponse(res) {
        if (res.ok) {
            alert('Login Successful!');
            this.props.updateTheUser(this.state.email);
        }
        else if (res.status === 401) {
            alert('Wrong Username or Password');
        }        
    }

    async sendLoginRequest(data) {
        await fetch('http://localhost:8000/login/',{
            method: 'POST',headers: { 'Content-Type': 'application/json'},body: data,})
        .then(this.handleResponse)
        .catch(function(error) {
            alert('Server error,please try again.');
            console.error(error);
        });
    }

    handleSubmit(event) {
        const data = `{"email": "${this.state.email}","password": "${this.state.password}"}`
        this.sendLoginRequest(data);
    }

    render () {
        return (
            <div id="container" className="col-md-12" align="center">
                <div id="vertical-center-div"className="col-sm-4 card bg-light">
                    <Form onSubmit={this.handleSubmit}>
                        <Form.Label className="display-4 text-secondary">Login</Form.Label>
                        <Form.Group controlId="formBasicEmail">
                            <Form.Control type="email" value={this.state.email} onChange={this.handleEmailChange} placeholder="Email" required/>
                        </Form.Group>
                        
                        <Form.Group controlId="formBasicPassword">
                            <Form.Control type="password" value={this.state.password} onChange={this.handlePasswordChange} placeholder="Password" required/>
                        </Form.Group>
                        <Form.Group controlId="formBasicCheckbox">
                            <Form.Check type="checkbox" label="Remember me" />
                        </Form.Group>
                        <Button id="submitButton" variant="primary" type="submit">
                            Submit
                        </Button>
                    </Form>
                </div>
            </div>
        )
    }
}

export default Login;

Dashboard.js:

class Dashboard extends Component {
    constructor(props) {
        super(props);
        this.state = {
            expenses: [],incomings: []
        }
    }

    render () {
        return (
            <>
            <p className="display-4">Dashboard</p>
            </>
        )
    }
}

export default Dashboard;

解决方法

似乎,在Login.js中,您需要防止使用event.preventDefault()的默认提交行为

handleSubmit(event) {
        event.preventDefault()
        const data = `{"email": "${this.state.email}","password": "${this.state.password}"}`
        this.sendLoginRequest(data);
    }

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...