[英]Countless http requests created in MERN stack application
我不知道是什么原因造成的,它幾乎每半秒發送一次新請求。 我以為這是因為我在render方法中調用了動作,但事實並非如此,試圖在componentDidMount
調用它,結果相同。
這是代碼:
行動:
export const getComments = () => dispatch => {
dispatch({
type: GET_COMMENTS
})
fetch(`${API_URL}/comments`,
{ method: 'GET', headers: {
'content-type': 'application/json'
}})
.then((res) => res.json())
.then((data) => dispatch({
type: GET_COMMENTS_SUCCESS,
payload: data
}))
.catch((err) => dispatch({
type: GET_COMMENTS_FAILED,
payload: err
}))
}
由於我需要在調用評論操作之前加載帖子ID,因此將其放在render方法中:
componentDidMount() {
const { match: { params }, post} = this.props
this.props.getPost(params.id);
}
render() {
const { post, comments } = this.props;
{post && this.props.getComments()}
return <div>
...
這是路線:
router.get("/comments", (req, res) => {
Comment.find({})
.populate("author")
.exec((err, comments) => {
if (err) throw err;
else {
res.json(comments);
}
});
});
您的getComments()函數在渲染期間正在運行。 該操作中使用的調度將導致重新渲染,從而導致getComments()再次觸發,從而產生無限循環。
與其在render()函數中獲取注釋,不如在componentDidMount生命周期掛鈎中獲取它們,然后在render函數中僅顯示props中的注釋;
getComments()
正在調用http請求,因此應將其移至componentDidMount
生命周期掛鈎。 這應該工作:
componentDidMount() {
const { match: { params } = this.props
this.props.getPost(params.id);
this.props.getComments()
}
render() {
const { post, comments } = this.props;
{post && comments}
return <div>
...
安裝組件后,將從props.match
中檢索參數,並獲取Post和Comments。 然后使用redux調度發布和注釋數據,並可以在連接的組件的render
方法中對其進行訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.