[英]How to fetch data from mongodb in MERN
我不確定您的問題到底是什么,您將用戶設置為數組,但是在render方法中將其視為“文本”,請嘗試使用map方法遍歷每個用戶並顯示每個用戶的信息(如果您這樣做)從API獲取信息時遇到問題,請嘗試將客戶端package.json中的代理設置為API端口,並在react ComponentDidMount生命周期中使用操作。
您可以使用如下所示的方式,將頭添加到axios請求中,將'crossDomain'設置為:true以克服cors錯誤。
export default class Profile extends Component{
constructor(props){
super(props);
this.state = {
users: []
}
}
conmponentDidMount(){
axios.get('/api/account/profile',{ headers: { 'crossDomain': true, 'Content-Type': 'application/json' } })
.then(res=> {
this.setState({ users: res.data }).then(profileState => {
console.log(JSON.stringify(this.state.users))
}); //It sets the state asynchronously
})
}
render(){
<div>
<div className="user-details">
{
this.state.users.map(user =>
<tr>
<td>Username: </td>
<td>{user.name}</td>
</tr>
)
}
</div>
</div>
}
}
謝謝,實際上我只是使用了this.state.user.name
而沒有映射從數據庫中顯示
<strong>Name:</strong>{this.state.user.name}<br/>
在api中,我在url中獲取用戶ID,以從會話中獲取當前用戶/活動用戶。
axios.get('/api/account/profile/info?id=' +id)
.then(res => {
this.setState({ user: res.data.user });
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.