【发布时间】:2016-10-27 14:49:20
【问题描述】:
我在输入文本字段上有一个 onBlur 自动保存记录;数据结构是一个包含一系列项目的文档。如果我快速更改项目的第一列,然后快速更改第二列,则第一列的保存将导致更新,这将重新加载两个输入字段。
如何防止第一次保存重新加载整行以便保存两个列值?
这是代码 sn-p(我用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")
);
我也有代码作为codepen:http://codepen.io/tommychheng/pen/zBNxeW?editors=1010
【问题讨论】:
-
item总是并且只有属性one和two?或者item可以有更多或更少的属性吗? -
item 有固定数量的属性(只有一个和两个)和输入字段。
标签: javascript reactjs flux autosave