[英]How to get the data in a fetch before the component get mount?
我正在嘗試從 Node 中的本地服務器獲取數據,但我的問題是,當我調用組件的渲染函數時,狀態中的數組用戶似乎是空的,因此不會像我一樣在屏幕上渲染用戶想,奇怪的是,我在 fetch 中的console.log(users)
確實給我帶來了數據,但是當我在渲染上這樣做時並沒有給我帶來任何東西:
這是到目前為止的代碼:
import React, { PureComponent } from "react";
import Nav from "./Nav";
import { IState, IProps } from "./Interfaces";
class Home extends PureComponent<IProps, IState> {
constructor(props: IProps) {
super(props);
this.state = {
users: [],
books: []
};
}
getUsers = async () => {
const response = await fetch(`http://localhost:5000/users`, {
headers: {
"Content-Type": "application/json"
}
});
const users = await response.json();
for (let user of users) {
this.state.users.push(user);
}
console.log(this.state.users);
};
getBooks = async (id: number) => {
const token =
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlciI6Implc3VzIiwiaXNBZG1pbiI6dHJ1ZSwiaWF0IjoxNTc2NjgzNTkwfQ.1FWmtj-fCsqSza_pwfewIpp3zQ50BxDagRTvrh5x3cU";
const response = await fetch(`http://localhost:5000/bookUser/${id}/books`, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json"
}
});
const books = await response.json();
this.setState({ books });
};
onUserSelection = (id: number) => this.getBooks(id);
componentDidlMount() {
this.getUsers();
}
render() {
const { users } = this.state;
console.log(this.state.users);
return (
<div>
<Nav username={this.props.username} />
<h1>Hello {this.props.username}</h1>
<table>
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
{users.map(u => (
<tr
key={u.user_id}
onClick={() => this.onUserSelection(u.user_id)}
>
<td>{u.user_id}</td>
{console.log(u.user_id)}
<td>{u.username}</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
export default Home;
正如之前在 Sameer 的評論中提到的,您希望在設置狀態時避免使用推送。 這樣做不會觸發重新渲染。
而不是你正在做的this.state.users.push(user)
,用這個替換它(和它后面的 console.log ):
this.setState(prevState => ({
users: [...prevState.users, user]
}, console.log("updated users", this.state.users)));
這里有些不同。
setState 中的第一個參數接受一個函數。 該函數中公開了一個參數,即您之前的狀態 (prevState)。 使用擴展運算符,您可以使用舊用戶和所有新用戶創建一個新數組。
其次,由於 setState 的異步特性,您不能期望在 setState 函數之后立即運行 console.log() 。 相反,您可以將回調函數(在本例中為 console.log)作為第二個參數傳遞給 setState & 它將在完成時觸發。
使用setState
在 state 中填充用戶
this.setState({
users: users
})
並在地圖之前渲染,執行此操作
{
users.length>0 &&
users.map(u => ( <tr key={u.user_id} onClick={() => this.onUserSelection(u.user_id)} > <td>{u.user_id}</td> {console.log(u.user_id)} <td>{u.username}</td> </tr> ))
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.