【问题标题】:Creating dynamic table with data fetched from API in JS React Bootstrap使用从 JS React Bootstrap 中的 API 获取的数据创建动态表
【发布时间】:2021-08-18 04:52:28
【问题描述】:

我在 JS 方面完全是绿色的,但我有一个小问题。我想创建包含汽车信息的动态表。我从我的朋友 API 获取数据(我将在帖子底部显示完整的 json),我可以在日志控制台中显示它。但我不知道如何将其插入表中。这是我的代码:

const CarsClient = () => {

const [car, setCars] = useState({});

const getCarsList = async () => {
    const response = await fetch('http://localhost:3000/api/catalog/car?fbclid=IwAR0lOlJP-1kBKvQzn8GQ_3oYqVN5kTbRrlctDO6T10CJcumcPWfa7WVugQw');
    const jsonData = await response.json();
    setCars(jsonData);
    console.log(jsonData);
  };
useEffect(() => {
    getCarsList();
}, []);

    (...)
}
const renderCars = (car, index) => {
    return(
        <tr key={index}>
            <td>{car.id}</td>
            <td>{car.cost}</td>
    )
}
return (
    <>
<Container className="cont">
  (...)
      <ReactBootStrap.Table striped bordered hover>
            <thead>
                <tr>
                <th>#</th>
                <th>ID</th>
                <th>Price</th>
                </tr>
            </thead>
            <tbody>
                {
                    car.map(renderCars)
                }
            </tbody>
        </ReactBootStrap.Table>
        </Col>
    </Row>    
</Container>             
  </>
)

} 导出默认 CarsClient

这是 JSON: {"car":[{"id":1,"cost":250,"VIN":2334433,"availability":true,"CarModelId":1,"CarModel":{"id":1,"name ":"X5","fuel":"ON","body":"SUV","productionYear":2020,"enginePower":200,"MakeId":1,"Make":{"id":1 ,"名称":"BMW"}}},{"id":2,"cost":275,"VIN":2334433,"availability":true,"CarModelId":2,"CarModel":{"id ":2,"name":"Q7","fuel":"ON","body":"SUV","productionYear":2019,"enginePower":220,"MakeId":2,"Make": {"id":2,"name":"AUDI"}}}]}

我有这个错误:CarsClient.js:96 Uncaught TypeError: car.map is not a function

【问题讨论】:

    标签: javascript reactjs bootstrap-4 fetch react-bootstrap


    【解决方案1】:

    car这里是一个对象而不是一个数组,所以你应该执行以下操作
    在你getCarList:

    setCars(jsonData.car)
    

    关于你的状态定义:

    const [car, setCars] = useState([]);
    

    【讨论】:

    • 现在我收到以下错误:TypeError: car.map is not a function
    • 那可能是因为你的getCarList 是异步的,所以当你第一次渲染时它没有任何数据。更新答案
    • 它更多的是您需要更新的状态的初始条件,以便它是一个数组而不是一个对象,因为您想使用 map 遍历它。还建议将其重命名为 cars
    • 好的,小更新,现在我有以下错误:TypeError: response.json is not a function
    • 这将是您的 fetch 验证从 fetch 和您尝试调用的 api 返回的内容的问题
    【解决方案2】:

    最好将汽车对象定义为:

    const [car, setCars] = useState([]);
    

    并循环遍历数组:

    顺便说一句,我在没有 api 调用的情况下复制了它,问题出在 car.car.map 上。看看下面的链接:
    https://codesandbox.io/s/patient-wildflower-pjfbk?file=/src/Car.js:848-865

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2021-04-10
      • 2021-02-12
      相关资源
      最近更新 更多