Reactにデータベースの更新と削除がAjax経由で処理される単純なデータベースがあります。Reactで更新後に再レンダリングできません
レコードコンポーネントのAjax呼び出しが成功すると、更新または削除されたレコードがレコードコンポーネントに渡され、すべてのレコードが表示されます。
以下のハンドルメソッドは、レコードの状態を更新し、結果を再レンダリングします。
私の問題は、handleDeleteメソッドがうまくいき、削除されたレコードを使わずにレコードを再描画するのに対し、handleUpdateメソッドはページを更新するまで未更新のレコードを残さないということです。
なぜ、handleUpdateのsetStateが結果を再レンダリングしないのでしょうか?以下は
はコードです:
class Sites extends React.Component {
constructor (props) {
super(props);
this.handleUpdate = this.handleUpdate.bind(this);
this.handleDelete = this.handleDelete.bind(this);
this.state = {records: this.props.records};
}
handleUpdate (record) {
let records = this.state.records;
let index = records.map((x) => {return x.id}).indexOf(record.id);
records.splice(index, 1, record);
this.setState({records: records}); # this doesn't re-render the results
}
handleDelete (record) {
let records = this.state.records;
let index = records.map((x) => {return x.id}).indexOf(record.id);
records.splice(index, 1);
this.setState({records: records}); # this re-renders the results
}
render() {
let records = this.state.records.map((record) => {
return (
<Record record={record} key={record.id} handleUpdateRecord={this.handleUpdate} handleDeleteRecord={this.handleDelete}/>
);
});
return (
<div className="col-sm-9">
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>City</th>
<th>State</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{records}
</tbody>
</table>
</div>
);
}
}
「 」実装を提供できますか? –
あなたは 'splice'によって状態を変更するべきではありません。 'let records = this.state.records.slice();'を追加する必要があります。 handleUpdateをログに記録しましたか? –