javascript - 如何在 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'
/>
...
);
})}
解决方案
推荐阅读
- github-actions - 如果我在主(主)和另一个分支中有两个版本的 workflow.yaml 会发生什么?
- html - 使用 div 嵌入脚本无响应/全屏
- python - 值错误:形状
- c# - 如何将 Logger 传递给 ASP.NET 5.0 应用程序中的 Startup 类?
- android - Gradle 恶魔启动数百个虚拟机
- javascript - 用于验证网站上的电子邮件的基本概念是什么?
- aws-lambda - 开玩笑,带有中间件的测试处理程序
- spring-boot - Spring WebFlux Kotlin OAuth2 CORS
- arrays - 按 Octave 中的列对矩阵进行排序
- rust - 引用上指定的生命周期是否表示引用或对象将存在多长时间?