无法获取ReactJS组件进行更新

时间:2018-07-26 11:38:24

标签: javascript reactjs

一旦进行了fetch()调用并产生了来自fetch()调用的错误消息,我就尝试更新页面上的区域。提交表单按钮后,将执行fetch()调用。

fetch()完成后,我写了ErrorMessage(data['Result']);,我认为它将通过data['Result']作为props。您可以在渲染中看到我有<ErrorMessage error="Original Message" />,这是我认为会随来自fetch()调用的消息而更新的内容。

请在下面为此页面查看我的完整代码:

import React from 'react';
import './css/LoginForm.css';

function ErrorMessage(props) {
    return (
        <p id="error-message">
            {props.error}      
        </p>
    )
}

class LoginForm extends React.Component {

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

        this.handleInputChange = this.handleInputChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleInputChange(event) {
        const target = event.target;
        const value = target.value;
        const name = target.name;

        this.setState({
            [name]: value
        });
    }

    handleSubmit(event) {
        event.preventDefault();
        var loginData = {
            username: this.state.username,
            password: this.state.password
        }

        fetch('/login', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                loginData: loginData
            })
        })
        .then(function(response) {
            return response.json();
        })
        .then(function(data) {
            if (data['Result']) {
                console.log(data['Result']);
                ErrorMessage(data['Result']);
            }
        })
        .catch(function(error) {
            console.log('Error: ', error);
        });
    }

    render() {
        return (
            <div id="login-form-container">
                <form id="login-form" onSubmit={this.handleSubmit} method="POST">
                    <ErrorMessage error="Original Message" />
                    <input
                        type="text"
                        name="username"
                        placeholder="username"
                        autoComplete="username"
                        onFocus={(e) => e.target.placeholder = ''}
                        onBlur={(e) => e.target.placeholder = 'username'}
                        value={this.state.username}
                        onChange={this.handleInputChange}
                        required
                    ></input>
                    <input
                        type="password"
                        name="password"
                        placeholder="password"
                        autoComplete="current-password"
                        onFocus={(e) => e.target.placeholder = ''}
                        onBlur={(e) => e.target.placeholder = 'password'}
                        value={this.state.password}
                        onChange={this.handleInputChange}
                        required
                    ></input>
                    <button type="submit" name="submit">Login</button>
                    <p className="forgotten-password">Forgotten your password?</p>
                </form>
            </div>
        );
    }

}

export default LoginForm;

这可能是完全错误的,因为我正在努力准确地了解组件在ReactJS中的工作方式,因此我向您致歉。谢谢您的见识。

1 个答案:

答案 0 :(得分:2)

fetch完成后创建组件不会影响render组件的LoginForm方法返回的内容。

您可以改为将错误消息设置为LoginForm状态,并将其用作render方法中ErrorMessage组件的道具。

示例

class LoginForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: "",
      password: "",
      error: "Original Message"
    };

    this.handleInputChange = this.handleInputChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  // ...

  handleSubmit(event) {
    event.preventDefault();
    var loginData = {
      username: this.state.username,
      password: this.state.password
    };

    fetch("/login", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        loginData: loginData
      })
    })
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        if (data["Result"]) {
          console.log(data["Result"]);
          this.setState({ error: data["Result"] });
        }
      })
      .catch((error) => {
        console.log("Error: ", error);
      });
  }

  render() {
    return (
      <div id="login-form-container">
        <form id="login-form" onSubmit={this.handleSubmit} method="POST">
          <ErrorMessage error={this.state.error} />
          <input
            type="text"
            name="username"
            placeholder="username"
            autoComplete="username"
            onFocus={e => (e.target.placeholder = "")}
            onBlur={e => (e.target.placeholder = "username")}
            value={this.state.username}
            onChange={this.handleInputChange}
            required
          />
          <input
            type="password"
            name="password"
            placeholder="password"
            autoComplete="current-password"
            onFocus={e => (e.target.placeholder = "")}
            onBlur={e => (e.target.placeholder = "password")}
            value={this.state.password}
            onChange={this.handleInputChange}
            required
          />
          <button type="submit" name="submit">
            Login
          </button>
          <p className="forgotten-password">Forgotten your password?</p>
        </form>
      </div>
    );
  }
}