React在状态改变后不重新渲染?

时间:2018-05-15 11:43:12

标签: javascript reactjs

如果React在每次状态更改后重新渲染组件,为什么在handleFormSubmit()中提交newUser后它是否正在使用此代码?我看到它在react控制台上更新了,并且它被发布到数据库但是我只在实际重新加载页面时才在DOM中看到它,当我更改状态并提交表单时,不应该更新组件吗? / p>

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

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      users: [],
      newUser: {
        name: '',
        email: '',
        country: '',
        img: ''
      }
    };

    this.handleFormSubmit = this.handleFormSubmit.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  fetchData() {
    fetch('http://127.0.0.1:3000/')
      .then((res) => {
        return res.json();
      })

      .then(users =>
        this.setState({
          users: users
        }))
      // handle the error
      .catch(err => console.log(err));
  }

  componentDidMount() {
    this.fetchData();
  }

  // this changes all the inputs
  handleInput(e) {
    const { value } = e.target;
    const { name } = e.target;
    this.setState(
      prevState => ({
        newUser: {
          ...prevState.newUser,
          [name]: value
        }
      }),
      () => console.log(this.state.newUser)
    );
  }

  handleFormSubmit(e) {
    e.preventDefault();
    const userData = this.state.newUser;
    this.setState({
      users: [...this.state.users, userData]
    });

    fetch('http://127.0.0.1:3000/register', {
      method: 'POST',
      body: JSON.stringify(userData),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      }
    }).then((response) => {
      response.json().then((data) => {
        console.log('Successful' + data);
      });
    });
  }

  render() {
    const { users } = this.state;
    // const users = 0;
    return (
      <div style={style}>
        {/* <SingUp /> */}

        <div style={styleForm}>
          <h1>Sign Up!</h1>
          <form onSubmit={this.handleFormSubmit}>
            <input
                type="text" placeholder="name" name="name"
                value={this.state.newUser.name} handleChange={this.handleInput} onChange={this.handleInput}
            />

            <input
              type="text" placeholder="email" name="email"
                value={this.state.newUser.email} handleChange={this.handleInput} onChange={this.handleInput}
            />

            <input
              type="text"
              placeholder="country"
              name="country"
              value={this.state.newUser.country}
              handleChange={this.handleInput}
              onChange={this.handleInput}
            />

            <input
                type="text" placeholder="img url" name="img"
                value={this.state.newUser.img} handleChange={this.handleInput} onChange={this.handleInput}
            />

            <button onSubmit={this.handleFormSubmit}>OK</button>
          </form>
        </div>

        <div style={style} />
        {users.length > 0 ? (
          users.map((user) => {
            return (
              <div>
                <User
                    key={user.email} email={user.email} fullName={user.full_name}
                    country={user.country} img={user.img} created={user.created_at}
                />
              </div>
            );
          })
        ) : (
          <p> no users found</p>
        )}
      </div>
    );
  }
}

const User = (props) => {
  return (
    <div style={style}>
      {/* <p>{props.email}</p> */}
      <h4>{props.fullName}</h4>
      <p>{props.country}</p>
      <p>{props.created}</p>
      <img src={props.img} alt="" />
    </div>
  );
};

export default App;

1 个答案:

答案 0 :(得分:0)

newUser数据与您提供给用户组件的数据不匹配。如果您的API响应格式为

{
    email: '',
    full_name: '',
    country: '',
    img: ''
    created_at: '',
}

您必须设置状态为响应,而不是来自newUser状态

handleFormSubmit(e) {
    e.preventDefault();

    fetch('http://127.0.0.1:3000/register', {
      method: 'POST',
      body: JSON.stringify(userData),
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      }
    }).then((response) => {
      response.json().then((data) => {
        console.log('Successful' + data);
        this.setState({
           users: [...this.state.users, data]
        });
      });
    });
  }