错误无法编译未定义no-undef

时间:2018-04-28 14:27:04

标签: javascript json reactjs api

开发一个可接受以下API值的登录表单:https://api.myjson.com/bins/11unjr

...目前,密码字段为空,因此接受任何密码。我收到错误:编译失败' userName'未定义no-undef; “pwd”未定义为no-undef

代码:

import React, { Component } from 'react';
import './Login.css';

class Login extends Component {  

    state = { data: [] }

    componentWillMount(){
        fetch('https://api.myjson.com/bins/5432', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-type': 'application/json',
                'Authorization': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiR3JlZyIsInVuaXF1ZV9uYW1lIjoiZ2dyYWZmIiwibmJmIjoxNTI0ODM5Nzc1LCJleHAiOjE1MjQ5MjYxNzV9.xhvdfaWkLVZ_HLwYQuPet_2vlxNF7AoYgX-XRufiOj0'
            },
            body: JSON.stringify({
                username: 'userName',
                password: 'pwd',
            })
        }

        ) /*end fetch */
        .then(results => results.json()) 
        .then(data => this.setState({ data: data }))   
      }

    //render component
    render() {
    console.log(this.state.data);
        return (
            <div>
                <div className="container">

                <div className="loginContainer">
                    <h2>Member Login</h2>
                    <form>
                        <div className="form-group">
                            <label for="username">User Name:</label>
                            <input type="text" class="form-control" id="{userName}" placeholder="Enter User Name" name="userName" />
                        </div>
                        <div className="form-group"> 
                            <label for="pwd">Password:</label>
                            <input type="password" class="form-control" id="{pwd}" placeholder="Enter password" name="pwd" />
                        </div>
                        <div>
                            <button type="button" onClick="getInfo" className="btn btn-primary">Submit</button>
                        </div>
                   </form>
                </div>
            </div>
            </div> 

        );
      }

//function
        getInfo() {
            var username = document.getElementById('{userName}').value
            var password = document.getElementById('{pwd}').value

            if(username == {userName} && password == {pwd}) {
               window.location.href="MemberInfo.jsx";
                return
            }

        } 
//end function
}

export default Login
我可以帮忙解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

你不能将vanillaJS getElementById与react ...混合....首先你会得到非常奇怪的行为,因为React在JSDom中做了大量的DOM操作而不是真正的dom,(所以在循环中你可以让这个元素不在DOM中),其次你有一个奇怪的ID命名为dom ID {userName}这甚至会混淆jQuery而不是React。

您必须将输入转为受控输入https://reactjs.org/docs/forms.html,您将在其中绑定onChange侦听器,并在文档中传递来自event的值,这是一个很好的示例,如何实现这一点。