我正在構建一個基於React的項目用於學習目的。我被困在製作一個表格組件,它呈現自己,然後向mbaas後端發送一個Ajax請求,以獲取所有書籍條目並將每個條目填充到新行中。這是我到目前爲止所做的。請原諒大塊的代碼,但因爲我還沒有完全理解的方法,狀態和渲染(之間的相互作用),這裏是整個類:React組件問題與狀態,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>
);
}
}
現在BookRow是不是很有趣,只有onClick部分是相關的。它看起來像這樣:
<a href="#" onClick={() => this.deleteBook(this.props.id)}>{owner? `[Delete]` : ``}</a>
如果登錄用戶不是本書的出版者,則鏈接不應該是可見的。 onClick調用來自BookTable的方法deleteBook(id)。在成功的ajax上,它應該從state.books(數組)和render中刪除這本書。
我對initBooks方法特別困惑。我在填充狀態的循環之前添加了日誌,並在狀態更新時作爲回調。日誌#1和日誌#3的結果相同,日誌#2#4的結果相同。另外,如果我擴展日誌#2(在setState之前)或日誌#4,那麼這兩個顯示狀態= [1]。這有什麼意義?此外,如果您查看日誌#1#3 - 他們打印[]。我可能錯過了一些內部組件交互,但我真的不知道是什麼。
謝謝。
的setState動作是異步的,所以更改可能不會在this.state反映的時候了。 –