代码之家  ›  专栏  ›  技术社区  ›  Pranav

如何在reactjs中将类组件转换为功能组件?

  •  0
  • Pranav  · 技术社区  · 7 年前

    我有一个应用程序。js文件,它是用类组件编写的,但我想把它改成函数组件。从那时起,我就习惯了分类,也不熟悉功能组件。非常感谢您的任何建议。。。提前谢谢

    下面是我的应用程序。js文件

    import React from 'react';
    import './App.css';
    import Weather from './components/Weather';
    import Form from './components/Form';
    import Title from './components/Title';
    import ForecastDays from './components/forecast';
    import haze from './video/Haze.mp4';
    import Spinner from './components/Spinner'
    
    class App extends React.Component  { 
      constructor(props) {
        super(props);
    
        this.state = {
          isLoading: true,
          lat: '',
          lon: '',
          city: '',
          country: '',
          humidity: '',
          temperature: '',
          wind: '',
          description: '',
          error: ''
        }
      }
    
      componentDidMount = async () => {
        const {city, country} = this.state;
    
        // weatherbit
        const api_call3 = await fetch(`https://api.weatherbit.io/v2.0/current?` + 
        `?city=${city},${country}&days=5&key=${API_KEY3}`)
        const data3 = await api_call3.json();
        console.log('DATA I GET', data4)
    
        // weatherbit
        const api_call3 = await fetch(`https://api.weatherbit.io/v2.0/forecast/daily` + 
        `?city=${city},${country}&days=5&key=${API_KEY3}`)
        const data3 = await api_call3.json(); 
    
        this.setState({
            temperature: data4.data[0].temp,
            city: data4.data[0].city_name,
            country: data4.data[0].country_code,
            humidity: data4.data[0].rh,
            wind: data4.data[0].wind_spd,
            description: data4.data[0].weather.description,
            error: "",
            forecastdays: data3.data,
            isLoading: false
          })
    
    
      } 
    
      getWeather = async (e) => {
        e.preventDefault();
        const city = e.target.elements.city.value;
        const country = e.target.elements.country.value;
    
        // 1. weatherbit
        const api_call4 = await fetch(`https://api.weatherbit.io/v2.0/current?` + 
        `city=${city},${country}&key=${API_KEY3}`);
        const data4 = await api_call4.json();
    
        // 2. weatherbit
        const api_call3 = await fetch(`https://api.weatherbit.io/v2.0/forecast/daily` + 
        `?city=${city},${country}&days=5&key=${API_KEY3}`)
        const data3 = await api_call3.json();
    
        if(city && country) {
          this.setState({
            temperature: data4.data[0].temp,
            city: data4.data[0].city_name,
            country: data4.data[0].country_code,
            humidity: data4.data[0].rh,
            wind: data4.data[0].wind_spd,
            description: data4.data[0].weather.description,
            error: "",
            forecastdays: data3.data,
            isLoading: false
          })
        } else {
          this.setState({
            temperature: undefined,
            city: undefined,
            country: undefined,
            humidity: undefined,
            description: undefined,
            error: "Please Enter Some Value"
          })
        }
      }
    
      render() {
        const { forecastdays, isLoading, lat,lon,city,country,humidity,temperature,wind,
        description} = this.state;
    
        return (
          <div className="container">
            <div className="row">
    
                <div className="col-sm-4 form-container">
                  <Title/>
                  <Form getWeather={this.getWeather}/>
                </div>
              {isLoading && <Spinner/>}
              {!isLoading && (
                <React.Fragment>
             <div className="col-sm-8 image-container">
    
             {/* Weather Card */}
             <div className="background">
             <div className="container">
    
                 <div id="card" className="weather">
    
                     <div className="details">
                         {/* Weather Details */}
                          <div className="content" style={{width: '125px'}}>
                           <Weather
                             temperature={this.state.temperature}
                             city={this.state.city}
                             country={this.state.country}
                             humidity={this.state.humidity}
                             description={this.state.description}
                             wind={this.state.wind}
                             /> 
                          </div>
    
                         {/* Forecast Cards */}
    
                         <div className="content" style={{width: '210px'}}>
                           <ForecastDays forecastdays={forecastdays}/> 
                          </div>
                         {/* Forecast Cards Ends*/  }          
                     </div> 
    
                 </div>
             </div>
             </div>
             {/* Video Background Starts */}
             <div>
             { this.state.description == 'Haze' ? <video autoPlay muted loop id="myVideo">
             <source src={haze} type="video/mp4"/>
           </video>: ''}
             </div>
             {/* Video Background Ends */}
             </div>
             {/* Weather Card Ends */}
             </React.Fragment>
              )}
            </div>
          </div>
        );
      }
    }
    
    export default App
    

    我想把它转换成功能组件。。。请帮忙

    2 回复  |  直到 7 年前
        1
  •  1
  •   Bradley Richardson    7 年前
          const App = () => {
            const [isLoading, setIsLoading] = useState(true);
            const [weather, setWeather] = useState();
            const [error, setError] = useState();
            const [city, setCity] = useState();
            const [country, setCountry] = useState();
    
            useEffect(async () => {
              const result = await axios(
                "https://hn.algolia.com/api/v1/search?query=redux"
              );
              setData(result.data);
    
              const api_call3 = await fetch(
                `https://api.weatherbit.io/v2.0/forecast/daily` +
                  `?city=${city},${country}&days=5&key=${API_KEY3}`
              );
              const data3 = await api_call3.json();
              setWeather({
                temperature: data4.data[0].temp,
                city: data4.data[0].city_name,
                country: data4.data[0].country_code,
                humidity: data4.data[0].rh,
                wind: data4.data[0].wind_spd,
                description: data4.data[0].weather.description,
                forecastdays: data3.data
              });
              setIsLoading(false);
            });
            return null;
          };
    

    这可能会帮助你开始

        2
  •  0
  •   Maximiliano Poggio    7 年前

    我不会做你的工作,但我很高兴我能向你解释有状态(类)和无状态(函数/函数/任何你想叫它的东西,但没有状态)之间的区别。

    有状态组件有一个状态,也可以像容器一样使用。例如,您可以使用PageContainer,在componentDidMount中进行ajax调用以检索信息。

    无状态组件只是一个UI组件,没有任何副作用。曾经例如,你将有一个组件 <ShowInfo data={this.state.data} /> 这将在有状态组件中呈现。showinfo将是一个无状态组件。

    现在,您可以使用两者混合的钩子:它们在功能组件中包含状态。你可以在react docs中阅读大量文档。

        3
  •  0
  •   Nerdragen    7 年前

    首先,我要指出@marzelin的一些极端无益的行为。你应该感到羞耻,完全没有必要对它被称为 function vs functional 组成部分如果你在谷歌上搜索“功能组件”,你会得到人们称之为“功能组件”的结果,因为它的意思是一样的,没有区别,你只是在卑鄙。

    第二,为了回答你的问题,并且不需要额外的咆哮,你应该真正阅读 docs .总而言之,您当前的实现无法转换为函数(al)组件,主要是因为它有一个状态。为什么?函数(al)组件就是这样的,它只是一个函数,函数不能有状态,因为它是一个React组件,而不是一个整体Javascript组件。这也是调用函数(al)组件的原因 无国籍 组件。这些组件的主要用途是保持纯净,并在给定相同输入的情况下返回相同的输出。