【问题标题】:How I do use fetch API and store response in the state?我如何使用 fetch API 并在状态下存储响应?
【发布时间】:2022-01-21 12:04:18
【问题描述】:

我必须从服务器获取一个文件,在渲染组件后,其中包含来自城市的信息,我必须将它分配给状态中的 "citiesData"。但是没有收到数据,因为它在输出中没有看到。

我的抓取有什么问题?

服务器文件:

IranMap(该文件在获取时似乎有问题):

import React from 'react';
import './IranMap.css';
import CityModal from './CityModal';

class IranMap extends React.Component {

    state = {
        error: null,
        citiesData: null,
        selectedCity: null,
        isModalOpen: false,
    };

    componentDidMount() {
        fetch('http://localhost:9000/cities')
            .then(response => response.json())
            .then((result) => {
                this.setState({
                    citiesData: result
                });
            },
                (error) => {
                this.setState({
                    error
                });
                }
            )
    }

    cityClicked = (id) => (event) => {
        event.preventDefault();
        fetch(`http://localhost:9000/cities/${id}`,{method: 'GET'})
            .then(res => res.json())
            .then(result => {
                this.setState({
                    selectedCity: result,
                    isModalOpen: true
                });
            })
    }

    closeModal = () => {
        this.setState({
            isModalOpen: false,
        });
    };

    render() {
        if(this.state.error){
            return <div>Error: {this.state.error.message}</div>;
        }
        else {
            return (
                <div>
                    <div className="map-container">

                        {(this.state.citiesData || []).map((record) => (
                            <div
                                key={record.id}
                                className="city-name"
                                style={{
                                    top: `${record.top}%`,
                                    left: `${record.left}%`,
                                }}
                                onClick={this.cityClicked(record.id)}
                            >
                                {record.name}
                            </div>
                        ))}
                    </div>
                    <CityModal
                        city={this.state.selectedCity}
                        isOpen={this.state.isModalOpen}
                        onClose={this.closeModal}
                    />
                </div>
            );
        }
    }
}

export default IranMap;

这是我的输出。它应该是显示城市名称。但这是空的:

【问题讨论】:

  • 现在显示城市的问题解决了。

标签: reactjs json fetch


【解决方案1】:

我认为你正在尝试做的是渲染整个对象,你不能这样做,尝试渲染每个元素,我的答案的第二部分是你应该使用异步任务。

希望我的回答能指导你

【讨论】:

  • 谢谢。我只展示了我的代码的一部分。我想完成它。在渲染部分,每个元素都使用 map 方法进行映射。我只需要获取。我的问题只是关于如何获取。
猜你喜欢
  • 1970-01-01
  • 2019-01-29
  • 2019-09-02
  • 2021-02-26
  • 1970-01-01
  • 2018-09-18
  • 2017-02-07
  • 1970-01-01
  • 2018-09-15
相关资源
最近更新 更多