如何获取和显示 API 内容 Onsubmit

how to fetch and display API content Onsubmit

我正在使用 Reactjs 开发一个天气预报应用程序,但我遇到了困难 Fetching/displaying API 数据

我知道这个问题可能重复,但我已经在这个平台和其他地方查找了所有相关的 problems/solutions 但 none 解决了我的问题

//const API;
class WeatherApp extends React.Component{
    constructor(props){
        super(props);


        this.state = {
            location: "",
            reports:[]
        }
    }

//functions should be written outside the constructor method
    onSubmit = event => {
        //prevents default loading of the page when this function "onSubmit"
        //is called
        event.preventDefault();
        //saving the value of the textbox to a variable/const
        if(this.searchbox.value !== ""){ 
            const searchResult = this.searchbox.value;
            //update the state object
            this.setState({
                location: searchResult + " weather report"
            });
        }else{
            alert("please ensure that field is not empty!");
            return;
        }
    };



componentDidMount(){
    if(this.searchbox.value !== ""){ 
        fetch(`api.openweathermap.org/data/2.5/forecast?q=london,uk ${/*this.searchbox.value +*/ KEY}`,{
            method: "GET",
            dataType: "JSON",
            headers: {
              "Content-Type": "application/json; charset=utf-8",
            }
        })
        .then(response => { response.json() })
        .then(data => { 
            console.log(data);
            this.setState({ reports: data.list})
        });
    }
}


    render(){
        return(
            <div className="weather-app">
                <WeatherAppHeader />
                <div className="weather-body">
                    <div className="entry-pane">
                        <form onSubmit ={this.onSubmit} >
                            <input 
                                type="text" 
                                id="search-box"
                                placeholder="Location e.g Abuja, NG" 
                                size="40" 
                                ref={input => this.searchbox = input} />

                            <button type="submit" id="search-btn">search</button> 
                        </form>
                    </div>
                    <SearchedLocation  location={this.state.location} />
                    <WeatherReport  reports={this.state.reports} />
                </div>
            </div>

        );
    }
}

const WeatherAppHeader = () => ( 
    <nav> WEATHER FORECAST </nav>
);


const SearchedLocation = ({location}) => ( 
    <div className="searched-loc">{location}</div>
);
SearchedLocation.propTypes = {
    location: PropTypes.string
}


///Declaring state within the WeatherReport component 

const WeatherReport = ({reports}) => (
        <div className="weather-report" >
            <ul className="report-list">
            {reports.map(report => ( 
                <li key={report.id} className="daily-report">
                    <span className="daily-report-day">{report.day}</span><br/>
                    <span className="daily-report-icon">{report.icon}</span><br/>
                    <span className="daily-report-temp">{report.main.temp}</span>
                </li>
            ))}
            </ul>
        </div>

);

WeatherReport.propTypes = {
    report: PropTypes.array
}





ReactDOM.render(<WeatherApp />, document.getElementById('root'));

我想在提交表单时在浏览器控制台上显示来自 API 的所有数据,但无济于事......并且没有错误消息。请问有人可以帮忙吗?

在您的 fetch 调用之后,您在执行 .then(response => { response.json() }) 时没有正确地 returning response。只需删除花括号,这样你就可以执行隐式 return。否则,如果您使用大括号,则必须显式编写 .then(response => { return response.json() })

工作代码:

componentDidMount(){
    if(this.searchbox.value !== ""){ 
        fetch(`api.openweathermap.org/data/2.5/forecast?q=london,uk ${/*this.searchbox.value +*/ KEY}`,{
            method: "GET",
            dataType: "JSON",
            headers: {
              "Content-Type": "application/json; charset=utf-8",
            }
        })
        .then(response => response.json())
        .then(data => { 
            console.log(data);
            this.setState({ reports: data.list})
        });
    }
}