如何在React中使用多个表单字段自动保存?

时间:2016-06-24 21:52:37

标签: javascript reactjs flux autosave

我在输入文本字段上有一个onBlur,可以自动保存记录;数据结构是一个包含项目数组的文档。如果我快速更改项目的第一列然后更改第二列,第一列的保存将导致更新,这将重新加载两个输入字段。

如何防止第一次保存重新加载整行,以便保存两列值?

以下是代码段(我使用setTimeout模仿服务器保存):

class Store {
  static doc = {title: "test title", items: [{id: 1, one: "aa", two: "bbb"}, {id: 2, one: "yyy", two: "zzz"}]};

  static getDocument() {
    return this.doc;
  }

  static saveDocument(doc) {
      this.doc = doc;
  }

  static updateItemInDocument(item, callback) {
      var foundIndex;
      let updatedEntry = this.doc.items.find( (s, index) => {
        foundIndex = index;
        return s.id === item.id;
      });

      this.doc.items[foundIndex] = item;
      setTimeout(() => { console.log("updated"); callback(); }, 1000);
  }
};

const Row = React.createClass({
  getInitialState() {
    return {item: this.props.item};  
  },

  update() {
    let document = Store.getDocument();

    let updatedEntry = document.items.find( (s) => {
            return s.id === this.props.item.id;
        } );

     this.setState({ item: updatedEntry});
  },

  handleEdit() {
    this.setState({item: {
        id: this.props.item.id,
        one: this.refs.one.value,
        two: this.refs.two.value
      }
    });  
  },

  handleSave() {
    Store.updateItemInDocument(this.state.item, this.update);
  },

  render() {
    let item = this.state.item;
    console.log(item);
    return  <tr> <p>Hello</p>
        <input ref="one" type="text" onChange={this.handleEdit} onBlur={this.handleSave} value={item.one} />
        <input ref="two" type="text" onChange={this.handleEdit} onBlur={this.handleSave} value={item.two} />
      </tr>;
  }
});

const App = React.createClass({
  render() {
    let rows = Store.getDocument().items.map( (item, i) => {
      return <Row key={i} item={item} />;
    });

    return <table>
      {rows}
      </table>;
  }
});

ReactDOM.render(
  <App />,
  document.getElementById("app")
);

我还将代码作为代码集:http://codepen.io/tommychheng/pen/zBNxeW?editors=1010

1 个答案:

答案 0 :(得分:2)

问题源于tabbing out of an input field fires both the onChange and onBlur handlers

也许我误解了你的用例,但这就是我如何解决这个问题:

const Row = React.createClass({
  getInitialState() {
    return { item: this.props.item };
  },

  handleSave() {
    let item = {
      id: this.state.item.id,
      one: this.refs.one.value,
      two: this.refs.two.value
    }
    Store.updateItemInDocument(item); // Is it really necessary to use the callback here?
  },

  render() {
    let item = this.state.item;
    return (
      <tr>
        <p>Hello</p>
        <input ref="one" type="text" onBlur={this.handleSave} defaultValue={item.one} />
        <input ref="two" type="text" onBlur={this.handleSave} defaultValue={item.two} />
      </tr>
    );
  }
});

我从使用onChange处理程序切换到using a defaultValue