代码之家  ›  专栏  ›  技术社区  ›  merko

在mern堆栈应用程序中创建的无数http请求

  •  0
  • merko  · 技术社区  · 7 年前

    我不知道是什么原因造成的,它几乎每半秒发送一次新的请求。我想这是因为我在render方法中调用了我的action,但它没有,试图调用它 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
        }))
    }
    

    因为我需要在调用comment操作之前加载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);
          }
        });
    });
    
    2 回复  |  直到 7 年前
        1
  •  0
  •   Steve Vaughan    7 年前

    您的getComments()函数正在呈现期间运行。该操作中使用的分派导致重新呈现,导致getComments()再次激发,从而产生无限循环。

    与其在render()函数中获取注释,不如在componentdidmount生命周期钩子中获取它们,然后在render函数中简单地显示来自props的注释;

        2
  •  0
  •   Hinrich    7 年前

    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 并获取帖子和评论。然后使用redux,post和comments数据被发送,并可以在连接的组件的 render 方法。