首页 > 解决方案 > “无法在尚未安装的组件上调用 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

标签: javascriptreactjsaxios

解决方案


推荐阅读