簡體   English   中英

React App 在兩個地方使用相同的 function 但 API 調用不同。 我如何強制它每次都使用root?

[英]React App Using the same function in two places but the API call is different. How do I force it to use the root everytime?

所以我正在構建一個允許人們發表帖子和發表評論的應用程序。 我遇到了一個問題,如果我在兩個不同的地方使用相同的 addLikes 和 unLike function,第二個不起作用。

這是我的動作/控制器文件中的 function。

export const addLike = (id) => async (dispatch) => {
  try {
    const res = await axios.put(`api/posts/like/${id}`);

    dispatch({
      type: UPDATE_LIKES,
      payload: { id, likes: res.data },
    });
  } catch (err) {
    dispatch({
      type: POST_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

// Unlike

export const unLike = (id) => async (dispatch) => {
  try {
    const res = await axios.put(`api/posts/unlike/${id}`);

    dispatch({
      type: UPDATE_LIKES,
      payload: { id, likes: res.data },
    });
  } catch (err) {
    dispatch({
      type: POST_ERROR,
      payload: { msg: err.response.statusText, status: err.response.status },
    });
  }
};

當我在顯示所有帖子從最新到最舊的頁面上使用它時。 API 指向:

http://localhost:3000/api/posts/like/5ebba76c42f5fc2f98ebd94b

<Fragment>
      <div className='post bg-white p-1 my-1'>
        <div>
          <Link to={`/profile/${user}`}>
            <img className='round-img' src={avatar} alt='' />
            <h4>{name}</h4>
          </Link>
        </div>
        <div>
          <p className='my-1'>{text}</p>
          <p className='post-date'>
            Posted on <Moment format='YYYY/MM/DD'>{date}</Moment>
          </p>
          <button
            onClick={(e) => addLike(_id)}
            type='button'
            className='btn btn-light'
          >
            <i className='fas fa-thumbs-up'></i>{" "}
            <span>{likes.length > 0 && <span>{likes.length}</span>}</span>
          </button>
          <button
            onClick={(e) => unLike(_id)}
            type='button'
            className='btn btn-light'
          >
            <i className='fas fa-thumbs-down'></i>
          </button>
          <Link to={`/posts/${_id}`} className='btn btn-primary'>
            Discussion{" "}
            {comments.length > 0 && (
              <span className='comment-count'>{comments.length}</span>
            )}
          </Link>
          {!auth.loading && user === auth.user._id && (
            <button
              onClick={(e) => deletePost(_id)}
              type='button'
              className='btn btn-danger'
            >
              <i className='fas fa-times'></i>
            </button>
          )}
        </div>
      </div>
    </Fragment>

然后,我目前正在構建片段以顯示各個帖子,並且 API 將指向:

http://localhost:3000/posts/api/posts/like/5ebba76c42f5fc2f98ebd94b

      <div className='post bg-white p-1 my-1'>
        <div>
          <Link to={`/profile/${user}`}>
            <img className='round-img' src={avatar} alt='' />
            <h4>{name}</h4>
          </Link>
        </div>
        <div>
          <p className='my-1'>{text}</p>
          <p className='post-date'>
            Posted on <Moment format='YYYY/MM/DD'>{date}</Moment>
          </p>
          <button
            onClick={(e) => addLike(_id)}
            type='button'
            className='btn btn-light'
          >
            <i className='fas fa-thumbs-up'></i>{" "}
            <span>{likes.length > 0 && <span>{likes.length}</span>}</span>
          </button>
          <button
            onClick={(e) => unLike(_id)}
            type='button'
            className='btn btn-light'
          >
            <i className='fas fa-thumbs-down'></i>
          </button>
        </div>
      </div>
    </Fragment>

這兩個位置是:

              <PrivateRoute exact path='/posts' component={Posts} />
              <PrivateRoute exact path='/posts/:id' component={Post} />

如何強制相同的 function 每次都使用相同的確切路徑? 我不確定為什么第二種情況會在 api/ 前面添加額外的 /posts

您必須為 Axios 請求設置和配置默認基礎 URL。

例如:

// Axios configuration
axios.defaults.baseURL = "https://example.com/";

現在,每當您提出請求時,它都會自動將此默認 baseURL 前綴到您的每個請求。

喜歡: axios.put( api/posts/like/${id} )axios.put( https /${id} api );

  • 你怎么會在addLike方法上發送一個 Id。 如果你正在創建一個like,你不應該有它的 id。 動詞應該是post,而不是put。
  • 路線 /posts/:id 不應該是准確的,因為:id是動態的。
  • <span>{likes.length > 0 && <span>{likes.length}</span>}</span>這條線的目的是什么? 不應該是:
....
render () {
....
const likes = likes.length;
return (
....
<span>{likes}</span>
  • 有一些差距。 你用的是什么路由器?
  • 你如何設置 axios? 我推薦你使用npm i axios-es6-class

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM