在 MERN 堆栈应用程序中创建了无数的 http 请求
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
}))
}
因为我需要在调用评论操作之前加载 post 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 和注释。然后使用 redux 调度 post 和评论数据,并且可以在连接组件的 render
方法中访问。
我不知道是什么原因造成的,它几乎每半秒发送一次新请求。我以为是因为我在 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
}))
}
因为我需要在调用评论操作之前加载 post 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 和注释。然后使用 redux 调度 post 和评论数据,并且可以在连接组件的 render
方法中访问。