javascript - “无法在尚未安装的组件上调用 setState。” 将 Axios 与本地 API 一起使用时
问题描述
我正在尝试 console.log 托管在我的 LocalHost 上的 API。它是一个简单的 PHP API,在 XAMPP 上运行在与 React 不同的另一个端口上。然后 Axios 将导入 API 并将其分配给“产品”状态。
每次我 console.log API 时,它都会在控制台中正常显示。但是,它会加载两次。在两个控制台日志之间,是完整的错误:
index.js:1 Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the App component.
如何修改我的代码以完全消除此错误?
应用程序.js
import axios from "axios"
import React from "react"
const api = axios.create({
baseURL: `http://localhost/api/`,
})
class App extends React.Component {
constructor() {
super()
this.state = {
products: [],
}
api.get("/").then((res) => {
console.log(res.data)
this.setState({ products: res.data })
})
}
render() {
return (
<div>
{/* {this.state.products.map((product) => (
<div>
<h1>{product.id}</h1>
<h2>{product.subproduct}</h2>
<img src={product.img_url} class="product_img"></img>
<hr />
</div>
))} */}
</div>
)
}
}
export default App
解决方案
推荐阅读
- sonata-admin - SonataNewsBundle 在作曲家要求上抛出错误
- python - 如何在数据框中的循环上运行 if-else 语句
- json - SQL Server:从另一个 json 更新 json——通常
- vba - 如何在 VBA 中引用谷歌翻译结果框
- vba - 如何使用 VBA 在 Word 文档中搜索单词和短语列表并突出显示它们?
- git - 显示不同的 github 分支之间的差异?
- c# - 有没有办法知道它一次可以处理多少个用户,对于一个用 asp.net mvc 开发的网站?
- php - Laravel Passport 通过会话授予 API 令牌或限制对 js 文件的访问
- c - C:我需要遍历一个结构数组,但我不断收到错误校验和错误。我该如何解决?
- node.js - 在 Node JS 中使用 ssh2 保持连接保持活动状态