React Loader - 尝试在发出 api 请求时获取加载器并在获取响应时停止它

React Loader - Trying to get a loader when api request is made and to stop it when response is fetched

我想要的是,当我点击搜索按钮时,loader/spinner 应该出现在屏幕上直到数据被获取,当数据被获取时它应该消失。

Container.jsx

import React from 'react';
import './container.css'
import Weather from './weather';
var Loader = require('react-loader');
class Container extends React.Component {
    constructor(props) {
        super(props);

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

    componentDidMount() {
        this.setState.loaded=false;
    }

    continue = (e) => {
        this.setState({loaded:true});
        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],loaded:false});
                    })
                    .catch(err => console.log("error ",err)) 
        }
    };
    render() {
        console.log(this.state.weather);
        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} id="btn"><span class="fa fa-search"></span></button>
                    </label>
                </div>
                <div>
                    <Loader loaded={this.state.loaded}>
                      {weather}
                    </Loader>
                </div>
                
            </div>
        );
    }
}
export default Container;
我这里用的是react-loader 但是现在,它并没有按照我想要的方式发生,在单击它出现的 serach 按钮之前的某个时间,当获取数据时它停止了,我想在单击搜索按钮后发出 api 请求时启动它并且获取数据时停止。

首先你应该在获取数据后进行setState

this.setState({weather:[data],loaded:true});

其次还有另一种方法,您可以在 return 函数中分离代码,例如

{ !this.state.loaded ? <Loader loaded={false} options={options} className="spinner" />:{weather}}

根据 npm 中的文档,您可以查看它 react-loader