首页 > 解决方案 > 如何登录 ReactJs?

问题描述

如何登录 ReactJS?

我可能是 reactJS 的新手,所以我不知道如何正确登录 Reactjs。我尝试了类似下面的方法,但这不是正常工作。
如果有人可以帮助我完成我正在尝试做的事情,那就太好了。非常感谢你。

login-api 端点:http://localhost:8000/api/login


export default class App  extends Component{


  constructor(props) {
        super(props);
        this.state ={
            username: "",
            password: "",
        }
        this.onFormSubmit = this.onFormSubmit.bind(this)
    }

    onFormSubmit(values){
      console.log(values);

      const formData = new FormData();
      formData.append("username", values.username);
      formData.append("password", values.password);

        const options = {
            method: 'POST',
            body: formData
        };

      fetch('http://localhost:8000/api/login', options).then(() => {
        this.props.history.replace('/home')
        }).catch((error) => {
      console.log(this.props.state)
      })


    };


 render(){
    return(

    <div>

    <section class="login_part section_padding ">

                    <div class="login_part_form">

                            <Form onFinish={this.onFormSubmit}>
                                <div class="col-md-12 form-group p_star">
                                    <Form.Item name="username">
                                      <input type="text" class="form-control" placeholder="Username" required />
                                    </Form.Item>
                                </div>
                                <div class="col-md-12 form-group p_star">
                                  <Form.Item name="password">
                                    <input type="password" class="form-control"
                                        placeholder="Password" required />
                                   </Form.Item>
                                </div>
                                <div class="col-md-12 form-group">
                                    <button type="submit" value="submit" class="btn_3">
                                        log in
                                    </button>
                                </div>
                            </Form>


                        </div>
    </section>



    </div>

    )
 }
}

标签: javascriptreactjs

解决方案


So, looking at your code, i do not really see you changing your state anywhere. Looks like you lack some simple handlers, that will use setState method to modify the password and username in your state. You want to probably do it onChange of an input. After that in your onFormSubmit function you want to get the values from your state and send those to the server.


推荐阅读