onEditSubmit无法正确存储新值

时间:2019-04-06 15:42:42

标签: reactjs

我有一个应用程序,需要能够编辑物体上的喜欢数量。当我将新值提交到所需字段时,它将保留该值一秒钟,然后将其重置为原始值。

当我按下“编辑提交”方法上的“保存”按钮时,它将保留提交一秒钟,然后恢复为原始值。我希望它可以存储新值。

app.js代码:

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

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      dataSource: [],
      isLoaded: false,
    }
    this.onAdd = this.onAdd.bind(this);
    this.onEditSubmit = this.onEditSubmit.bind(this);
  }


  getDataSource() {
   return fetch("https://beer.fluentcloud.com/v1/beer")
     .then(response => response.json())
     .then(responseJson => {
       this.setState({
         isLoaded: true,
         dataSource: responseJson,
       });
       return responseJson;
     })
     .catch(error => console.log(error)); //to catch the errors if any
 }
 componentDidMount() {
   this.getDataSource();

 }
onAdd( name, likes) {
  const dataSource = this.getDataSource();
    dataSource.then(json => {
      json.push({
        name,
        likes
      });
      this.setState({dataSource: json});
    });
}


onEditSubmit (name, likes, originalName) {
  let dataSource = this.getDataSource();

  dataSource = this.state.dataSource.map(dataSource => {
    if (dataSource.name === originalName) {
      dataSource.name = name;
      dataSource.likes = likes;
    }
    return dataSource;
  });
  this.setState({ dataSource });
}

  render() {

    return (
      <div className="App">
      <h1>What is in My Fridge?</h1>

      <AddItem
        onAdd={this.onAdd}
      />

          {this.state.dataSource.map((dataSource) => (
            <SingleItem
              key={dataSource.name}
              name={dataSource.name}
              likes={dataSource.likes}
              onEditSubmit={this.onEditSubmit}
            />
          ))};




      </div>
    );
  }
}

export default App;

singleItem.js代码:

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


class SingleItem extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isEdit: false
    };


    this.onEdit = this.onEdit.bind(this);
    this.onEditSubmit = this.onEditSubmit.bind(this);

  }


  onEdit() {
    this.setState({ isEdit: true });
  }

  onEditSubmit(event) {
    event.preventDefault();

    this.props.onEditSubmit(this.nameInput.value, this.likesInput.value, this.props.name);
    this.setState({ isEdit: false });
  }

  render() {
    const { name, likes } = this.props;
    return (
      <div>
        {
          this.state.isEdit
            ? (
              <form onSubmit={this.onEditSubmit}>
              <input placeholder="Name" ref={nameInput => this.nameInput = nameInput} defaultValue={name}/>
              <input placeholder="Likes" ref={likesInput => this.likesInput = likesInput} defaultValue={likes}/>
              <button>Save</button>
                </form>
            )
            :   (
              <div>
      <li>
        {name} | Likes:  {likes}
      </li>
      <button onClick={this.onEdit}>Edit</button>

       </div>
)
}
      </div>
    );
  }
}

export default SingleItem;

AddItem.js:

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

class AddItem extends Component {
  constructor(props) {
    super(props);

    this.onSubmit = this.onSubmit.bind(this);
  }

  onSubmit(event) {
    event.preventDefault();
    fetch("https://beer.fluentcloud.com/v1/beer", {
      body: JSON.stringify({name: this.nameInput.value, likes: this.likesInput.value}),
      headers: {
        "Accept" : "application/json",
        "Content-Type": "application/json"
      },
      method: "POST"
    });

    this.props.onAdd(this.nameInput.value, this.likesInput.value);
    this.nameInput.value = '';
    this.likesInput.value = '';
  }

  render() {
    return (
      <form onSubmit={this.onSubmit}>
      <h3>Add Beer</h3>
        <input placeholder="Name" ref={nameInput => this.nameInput = nameInput} />
        <input placeholder="Likes" ref={likesInput => this.likesInput = likesInput}/>
        <button>Add</button>
        <hr />
      </form>
    );
  }
}

export default AddItem;

1 个答案:

答案 0 :(得分:0)

我看到您的getDataSource方法正在执行一些异步调用,并且您依赖结果,因此您需要像这样使用async/await

async onEditSubmit (name, likes, originalName) {
  let dataSource = await this.getDataSource();

  dataSource = this.state.dataSource.map(dataSource => {
    if (dataSource.name === originalName) {
      dataSource.name = name;
      dataSource.likes = likes;
    }
    return dataSource;
  });
  this.setState({ dataSource });
}

您的数据将被覆盖,因为您正在设置API调用后的状态,该调用会返回旧数据并异步发生。