私は研究目的でReactベースのプロジェクトを構築しています。私は自分自身をレンダリングし、mbaasバックエンドにすべてのブックエントリーを取得し、それぞれを新しい行に塗りつぶすためにajaxリクエストを送信するテーブルコンポーネントの作成に固執しています。ここまで私がこれまでに出てきたのはこれです。コードの大きな塊を許すが、私はまだ完全には)メソッド、状態(レンダリングの間の相互作用を理解していないため、ここでは、クラス全体でください:今BookRowはなく、非常に興味深いです状態、setState、レンダリングでコンポーネントに問題が発生する
class BooksTable extends Component {
constructor(props) {
super(props);
this.state = {
books: []
};
this.updateState = this.updateState.bind(this);
this.initBooks = this.initBooks.bind(this);
}
componentDidMount() {
let method = `GET`;
let url = consts.serviceUrl + `/appdata/${consts.appKey}/${consts.collection}`;
let headers = {
"Authorization": `Kinvey ${sessionStorage.getItem(`authToken`)}`,
"Content-Type": `application/json`
};
let request = {method, url, headers};
$.ajax(request)
.then(this.initBooks)
.catch(() => renderError(`Unable to connect. Try again later.`));
}
deleteBook(id) {
let method = `DELETE`;
let url = consts.serviceUrl + `/appdata/${consts.appKey}/${consts.collection}/${id}`;
let headers = {
"Authorization": `Kinvey ${sessionStorage.getItem(`authToken`)}`,
"Content-Type": `application/json`
};
let request = {method, url, headers};
$.ajax(request)
.then(() => this.updateState(id))
.catch(() => renderError(`Unable to delete, something went wrong.`));
}
updateState(id) {
for (let entry of this.state.books.length) {
if (entry.id === id) {
// Pretty sure this will not work, but that is what I've figured out so far.
this.state.books.splice(entry);
}
}
}
initBooks(response) {
console.log(`#1:${this.state.books});
console.log(`#2:${this});
for (let entry of response) {
this.setState({
books: this.state.books.concat([{
id: entry._id,
name: entry.name,
author: entry.author,
description: entry.description,
price: Number(entry.name),
publisher: entry.publisher
}])
},() => {
console.log(`#3${this.state.books}`);
console.log(`#4${this}`);
});
}
}
render() {
return (
<div id="content">
<h2>Books</h2>
<table id="books-list">
<tbody>
<tr>
<th>Title</th>
<th>Author</th>
<th>Description</th>
<th>Actions</th>
</tr>
{this.state.books.map(x =>
<BookRow
key={x.id}
name={x.name}
author={x.author}
description={x.description}
price={x.price}
publisher={x.publisher} />)}
</tbody>
</table>
</div>
);
}
}
のみonClick部分は関連しています。
<a href="#" onClick={() => this.deleteBook(this.props.id)}>{owner? `[Delete]` : ``}</a>
ログインしたユーザーが本の出版社でない場合、リンクは表示されません。 onClickはBookTableのメソッドであるdeleteBook(id)を呼び出します。成功したajaxでstate.books(配列)から本を削除してレンダリングする必要があります。
私は特にinitBooksメソッドについて混乱しています。ステートを更新するループの前にログを追加し、ステートが更新されたときのコールバックとしてログを追加しました。ログ#1とログ#3の結果は同じであり、ログ#2#4も同じです。また、ログ#2(setStateの前)またはログ#4を展開すると、両方とも状態= [1]と表示されます。これはどういう意味ですか?さらに、ログ#1#3を見ると、[]が印刷されます。おそらく内部コンポーネントのやりとりが欠けているかもしれませんが、実際には何が分かりませんか?
ありがとうございました。
setStateアクションは非同期なので、変更はthis.stateにすぐに反映されない可能性があります。 –