首页 > 解决方案 > 如何在 React 中使用特定 ID 进行 Axios 发布请求?

问题描述

我有一个图像滑块。对于每张图片,用户可以点击“喜欢”来支持(+1)或“不喜欢”来反对(-1)。我不知道如何使用 axios 来操作 json 文件。我正在使用 json-server 来模拟后端。

但似乎我只能运行 json-server 并打印出 results.json 或运行 localhost:3000 来查看我的 React 应用程序。此外,我无法为用户正在查看的每个图像(以及点击喜欢或不喜欢)发出单独的 POST 请求。

这是代码:

  // save axios get request in designs state

  const [designs, setDesigns] = useState([]);
  
  // get designs from results.json

  useEffect(() => {
    axios.get("json/results.json").then((response) => {
      setDesigns(response.data.results);
    });
  }, []);


  // now i want to send a "-1" to the results.json for that specific image
  // when a user clicks dislike

  const nextSlideandDislike = (id, vote) => {

    axios
      .post("http://localhost:3000/results/{id}", {
        vote: vote - 1,
      })

    // send downvote to results.json for this id
  };

在实际渲染中,我正在迭代设计:

      {designs.map((design, index) => {
        return (
          ...
            <FontAwesomeIcon
              className={styles.leftArrow}
              onClick={() => nextSlideandDislike(design.id, design.vote)}
              icon={faArrowCircleLeft}
            />    
        
            <p>DISLIKE IMAGE</p>

            <img
              className={styles.image}
              src={design.url}
              id={design.id}
              vote={design.vote}
              alt='design'
            />
            ...
        );
      })}

标签: javascriptreactjspostaxiosjson-server

解决方案


推荐阅读