我正在嘗試使用 react 和 express 制作一個全堆疊網路應用程式。atm 運行得很好,但這是我的問題:
所以我在后端快速運行。除了“/api”之外,所有路徑都被反應路由器使用。在“/api/blogposts”路徑中,我的 server.js 將查詢的結果發送到 mySQL 服務器。(我已經檢查過它并且這部分作業。如果我瀏覽到 /api/blogposts 我的瀏覽器會顯示一個包含我的 blogposts 表內容的 json)。
我的問題是讓它顯示在我的反應前端。我正在嘗試使用 fetch() 但它不起作用。這是我用于獲取博客文章的組件的代碼:
import React from 'react';
import './Blogposts.css';
import SingleBpost from '../SingleBpost/SingleBpost.js';
class Blogposts extends React.Component {
constructor(props) {
super(props);
this.state = {
receivedPosts: {}
};
}
generateBlogpost() {
fetch("/api/blogposts")
.then((data) => {
console.log(data);
})
.then((results) => {
this.state.receivedPosts = results;
});
return this.state.receivedPosts;
}
render() {
return(
<div id="Blogposts">
{this.state.generateBlogpost()}
</div>
);
}
}
export default Blogposts;
只是為了澄清渲染方法中的 {this.state.generateBlogpost()} 只是為了檢查我現在是否可以獲取資料。一旦成功,我會將它輸入到另一個組件的 props 中,如下所示:
<SingleBpost title={this.state.generateBlogpost().title} date={this.state.generateBlogpost().date} author={this.state.generateBlogpost().author} body={this.state.generateBlogpost().body} />
無論如何:有誰知道為什么這不起作用?我已經嘗試了一些東西,但我就是無法讓它作業。我究竟做錯了什么?
在此先感謝您的幫助!
uj5u.com熱心網友回復:
您需要receivedPosts在 fetch 函式中設定變數的狀態,如下所示:
this.setState({receivedPosts: results});
此外,您可以通過添加以下函式generateBlogpost()在組件加載時呼叫該Blogposts函式:
componentDidMount() {
this.generateBlogpost();
}
uj5u.com熱心網友回復:
這個沒用
.then((results) => {
this.state.receivedPosts = results;
});
return this.state.receivedPosts;
}
//相反,您應該使用 setState({receivedPosts: data.data})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/385457.html
上一篇:嘗試將多個外鍵添加到單個表時出錯
