完成提交事件后,React.js组件不会重新呈现

时间:2017-09-13 14:42:02

标签: reactjs components

我开始学习React.js。因此,我编写了登录表单,我们将在用户访问该页面时显示该主页,并在用户成功登录时显示该主页。

基本上,我的项目结构如下:

  • node_modules
  • 公共
  • SRC
    • 部件
      • Login.jsx
    • App.js
    • index.js

代码如下:

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter } from 'react-router-dom';
import registerServiceWorker from './registerServiceWorker';
import 'antd/dist/antd.css';

ReactDOM.render(
    <BrowserRouter>
        <App />
    </BrowserRouter>, document.getElementById('root'));
registerServiceWorker();

App.js

import React from 'react';
import Home from './containers/Home';
import Login from './components/Login';

const App = () => (
    <Login />
);

export default App

Login.jsx

import React, { Component } from 'react';
import Home from '../containers/Home';

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


    handleUsernameChanged(event){
        this.setState({username: event.target.value});
    }

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

    isAuthenticated(){
        var userInfo = localStorage.getItem('userInfo');
        if(userInfo != null)
        {
            return true;
        }else{
            return false;
        }
    }

    render() {
        const isAlreadyAuthenticated = this.isAuthenticated();

        return (
            <div>
            {isAlreadyAuthenticated ? <Home /> : 
                (
                    <div>
                        <div className="login">
                            <div className="login-brand bg-inverse text-white">
                                <img src="assets/img/logo-white.png" height="36" className="pull-right" alt="" /> Login Panel
                            </div>
                            <div className="login-content form-input-flat">
                                <h4 className="text-center m-t-0 m-b-20">Great to have you back!</h4>
                                <form>
                                <div className="form-group">
                                    <input type="text" text={this.state.username} onChange={this.handleUsernameChanged.bind(this)}  className="form-control input-lg" placeholder="User Name" />
                                </div>
                                <div className="form-group">
                                    <input type="Password" text={this.state.password} onChange={this.handlePasswordChanged.bind(this)}  className="form-control input-lg" placeholder="Password" />
                                </div>
                                <div className="row m-b-20">
                                    <div className="col-md-12">
                                        <button onClick={(event) => this.handleClick(event)} className="btn btn-lime btn-lg btn-block">Sign in to your account</button>
                                    </div>
                                </div>
                                </form>
                            </div>
                        </div>
                    </div>
                )
            }
            </div>
        );
    }

    handleClick(event){
        event.preventDefault();
        var apiBaseUrl = "http://localhost:51171/api/user/validate?user_name=" + this.state.username + '&user_password=' + this.state.password;
        console.log(apiBaseUrl);
        fetch(apiBaseUrl)
            .then((resp) => resp.json()) // Transform the data into json
            .then(function(data) {
                console.log(data);
                if(data[0].status === "1")
                {
                    localStorage.setItem('userInfo', JSON.stringify(data));
                    this.setState();
                }else{

                }
            })
    }
}


export default Login;

我登录时遇到问题。登录成功,用户信息存储在LocalStorage中,但组件未重新呈现且主页未显示。 只有在成功登录尝试后手动刷新页面时才会显示主页。

您的善意建议深表感谢。感谢。

1 个答案:

答案 0 :(得分:0)

好吧,如果您想在单击提交按钮后重新呈现组件,则需要在表单提交时更改状态。我建议您将isAlreadyAuthenticated保留在当地州。所以你的州应该看起来像这样,

this.state={
            username:'',
            password:'',
            isAlreadyAuthenticated: false
        }

然后,当单击提交按钮时,将其设置为true,以便根据您的逻辑重新呈现组件并显示主组件。所以你的句柄提交回调应该是这样的,

handleClick(event){
        event.preventDefault();
        var apiBaseUrl = "http://localhost:51171/api/user/validate?user_name=" + this.state.username + '&user_password=' + this.state.password;
        console.log(apiBaseUrl);
        fetch(apiBaseUrl)
            .then((resp) => resp.json()) // Transform the data into json
            .then(function(data) {
                console.log(data);
                if(data[0].status === "1")
                {
                    localStorage.setItem('userInfo', JSON.stringify(data));
                    // Update the state here, so it triggers a rerender of the component.
                    this.setState({isAlreadyAuthenticated, true})
                    this.setState();
                }else{

                }
            })
    }

确保在取回时获得this.state.isAlreadyAuthenticated这样的状态。