首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >React.js -组件不会出现在按钮上,单击api获取的数据。

React.js -组件不会出现在按钮上,单击api获取的数据。
EN

Stack Overflow用户
提问于 2020-08-07 23:00:13
回答 1查看 47关注 0票数 0

我要做的是按一下按钮从天气API中获取数据,当数据被获取时,数据应该映射到组件中(即天气),然后只有该组件才会出现在屏幕上,现在我能够获取数据,但即使这样,组件也不会出现。

Container.jsx

代码语言:javascript
运行
复制
import React from 'react';
import './container.css'
import Weather from './weather';
class Container extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            location: "",
            weather: []
        };
    }
    handleChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
    };

    componentDidMount() {
    }

    continue = (e) => {

        const { location } = this.state;
        const rawurl = 'http://api.weatherstack.com/current?access_key=d8fefab56305f5a343b0eab4f837fec1&query=' + location;
        const url = rawurl;
        //e.preventDefault();
        if (location.length < 1) {
            return alert('Enter the details');
        }
        else {
                fetch(url)
                    .then(response => response.json())
                    .then(data =>{
                        this.setState({weather:data});
                    })
                    .catch(err => console.log("error ",err)) 
        }
    };
    render() {
        console.log(this.state);
        const weather =
        this.state.weather.length> 0 ? 
        this.state.weather.map(item => (<Weather location={item.location.name} temperature={item.current.temperature} weather={item.current.weather_descriptions[0]} windSpeed={item.current.wind_speed} windDegree={item.current.wind_degree} windDir={item.current.wind_dir} humidity={item.current.humidity} visibility={item.current.visibility} />
            ))
        :<span></span>
        return (
            <div id="container">
                <div class="searchicon">
                    <input type="search" placeholder="Enter City !!" type="text" name="location" value={this.state.location} onChange={this.handleChange}></input>
                    <label class="icon">
                        <button onClick={this.continue}><span class="fa fa-search"></span></button>
                    </label>
                </div>
                <div>
                {weather}
                </div>
                
            </div>
        );
    }
}
export default Container;

Weather.jsx

代码语言:javascript
运行
复制
import React from 'react';

class Weather extends React.Component {
    render(){
        return (
            <div id="result">
                <div id="location" class="insideres">
                    <div class="title">
                        Location
                    </div>
                    <div class="res">
                        {this.props.location}
                    </div>
                </div>
                <div id="Temperature" class="insideres">
                    <div class="title">
                        Temperature
                    </div>
                    <div class="res">
                    {this.props.temperature}
                    </div>
                </div>
                <div id="Weather" class="insideres">
                    <div class="title">
                        Weather
                    </div>
                    <div class="res">
                    {this.props.weather}
                    </div>
                </div>
                <div id="Windspeed" class="insideres">
                    <div class="title">
                        Wind Speed
                    </div>
                    <div class="res">
                    {this.props.windSpeed}
                    </div>
                </div>
                <div id="Wind_degree" class="insideres">
                    <div class="title">
                        Wind Degree
                    </div>
                    <div class="res">
                    {this.props.windDegree}
                    </div>
                </div>
                <div id="Wind_dir" class="insideres">
                    <div class="title">
                        Wind Direction
                    </div>
                    <div class="res">
                    {this.props.windDir}
                    </div>
                </div>
                <div id="Humidity" class="insideres">
                    <div class="title">
                        Humidity
                    </div>
                    <div class="res">
                    {this.props.humidity}
                    </div>
                </div>
                <div id="Visibility" class="insideres">
                    <div class="title">
                        Visibility
                    </div>
                    <div class="res">
                    {this.props.visibility}
                    </div>
                </div>
            </div>
        );    
    }
}
export default Weather;

我希望这个天气组件在从api中获取数据时出现,但是现在数据正在被获取,但它没有出现。

在上面的图像中,您可以看到我正在从api获取数据,但没有从搜索栏中获取该数据的天气组件。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-07 23:23:01

下面是使用钩子对组件的更新。我强烈建议您采用这种模式,因为使用起来要容易得多,但如果尚未采用这种模式,则需要使用React 16。你会注意到我:

  • 正在使用模板字符串,而不是连接字符串。这是最佳实践,如果天气变量的状态长度大于0,
  • 使用异步/等待,并承诺使用if语句呈现
  • 。如果不是,它将呈现容器组件.

代码语言:javascript
运行
复制
import "./container.css";

import React, { useState } from "react";

import Weather from "./weather";

const Container = () => {
    const [location, setLocation] = useState("");
    const [weather, setWeather] = useState([]);

    const fetchWeatherData = async () => {
        const url = `http://api.weatherstack.com/current?access_key=d8fefab56305f5a343b0eab4f837fec1&query=${location}`;
        if (location.length < 1) {
            return alert("Enter the details");
        } else {
            await fetch(url)
                .then((response) => response.json())
                .then((data) => {
                    setWeather(data);
                })
                .catch((err) => console.log("error ", err));
        }
    };

    if (weather.length > 0) {
        return weather.map((item) => (
            <Weather
                location={item.location.name}
                temperature={item.current.temperature}
                weather={item.current.weather_descriptions[0]}
                windSpeed={item.current.wind_speed}
                windDegree={item.current.wind_degree}
                windDir={item.current.wind_dir}
                humidity={item.current.humidity}
                visibility={item.current.visibility}
            />
        ));
    }

    return (
        <div id="container">
            <div className="searchicon">
                <input
                    placeholder="Enter City !!"
                    type="text"
                    name="location"
                    value={location}
                    onChange={(e) => setLocation(e.target.value)}
                />
                <label className="icon">
                    <button onClick={fetchWeatherData}>
                        <span className="fa fa-search" />
                    </button>
                </label>
            </div>
            <div>{weather}</div>
        </div>
    );
};

export default Container;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63310131

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档