React actual combat React + Redux implements a small weather forecast project

introduction

After a period of React learning, the development of React and Vue are indeed very different, but they are both MVVM frameworks, so it is not very difficult to get started, this time using React + Redux to develop a small weather forecast project. Source address: github.com/Beichenlove ...

"I am an old programmer who has been engaged in web front-end development for 6 years (my WeChat: web-xxq). At the beginning of this year, I spent a month finishing a full set of web front-end training courses that are best for self-study in 2019 Video + source code + notes + project combat), from the most basic HTML + CSS + JS to mobile HTML5 and various frameworks and new technologies are organized, packaged to each front-end partner, here is the gathering place of front-end learners , Welcome to beginners and advanced friends (all front-end tutorials follow my WeChat public number: web front-end learning circle, and follow the reply "2020" to receive).

Technology Stack

front end

  • React: MVVM framework for building interfaces
  • Redux: React's centralized state management, convenient and fast communication between components
  • Redux-thunk:  Commonly used redux asynchronous action middleware to handle asynchronous operations such as interface requests
  • styled-components: write CSS styles with componentized ideas
  • React-Redux : The component reads data from Redux and distributes actions to the store to update the data
  • antd : React-based UI library
  • immutable : a persistent data structure that prevents state objects from being incorrectly assigned

data collection

  • axios : Implement data interface request (simulate data with local json file)

Project preview

Page initialization

 

                                        

       

Choose a popular city

                                   

 

Search other cities

                                   

 

Implement function

 

Get local real-time status

Opening the page for the first time, according to the weather display of the city, we need to obtain a real-time status, here I use the Gaode Map Web JS API. First, we introduce index scripts in the public folder to add JS API entry script tags on the page;

 

// key值需在官网上申请
<script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.15&key=申请的key值">
</script> 复制代码

We use the official interface to achieve real-time positioning, because the weather information needs to be displayed for the first rendering, so use the componenDidMount life cycle function to make the request:

 

 

 

componentDidMount() 
{    // 防止作用域被修改    
    let _self = this;    
    if(_self.props.init){      
        //eslint-disable-next-line      
        AMap.plugin('AMap.CitySearch', function () {        
          //eslint-disable-next-line        
          var citySearch = new AMap.CitySearch()        
          citySearch.getLocalCity(function (status, result) {          
          if (status === 'complete' && result.info === 'OK') {            
            // 查询成功,result即为当前所在城市信息            
            _self.props.getCity(result.city)            
            _self.initWeather(_self.props.city)            
            _self.props.getInit()          
        }        
    })      
   })    
   }    
    else{      
    _self.initWeather(_self.props.city)    
   }
}复制代码

 

Here we need to make a judgment. If the city selection is changed from another page, returning to this page will reload and modify the changed city, so we use an identifier to judge whether it is the first time to load.

In addition, we note that there is a pit, React will be prompted to find AMapexamples of the problem. Use comments here

//eslint-disable-next-line

Write on the front line of each AMap class, and its eslint ignores this line of code and does not report an error

Get city weather information

Similar to getting the location information, I still use the API provided by the Gaode map. Here I attach the official website, lbs.amap.com/api/javascr ...

echarts data visualization

In order to display the temperature change trend, I used echarts line chart to visualize a data

Implementation code

 

 

 

initEchart(array) 
{    
    let domChart = this.dom;    
    //eslint-disable-next-line    
    var myChart = echarts.init(domChart);    
    let option = null;    
    option = {      
        xAxis: {        
        show: false,        
        type: "category",        
        axisLine: {          
            lineStyle: {            
            color: "#fff"          
        }        
    },        
    grid:{bottom: "20"}      
},      
    yAxis: {        
        show: false      
    },      
    series: [        
        {          
        data: array,          
        type: "line"        
        }      
    ]    
    }    
    myChart.setOption(option, true);  
}
复制代码

 

Use react-redux to operate Redux

react-redux is officially used by React to bind Redux, placing the Provider on the top layer, so that the store can be received by the following components

 

 

 

<Provider store={store}>      
   <Router>        
    <div>         
     <Route exact path='/' component={MainPage}></Route>          
     <Route exact path='/search' component={SearchCity}></Route>        
    </div>      
   </Router>
</Provider>复制代码

In the component, we use connect () to obtain the state or dispatch action in the store. Using its features, we can easily and conveniently change the city, historical search, and determine and change the identifier and other data.

Use of middleware thunk 

The default setting of redux is that dispatch can only accept one object parameter, and functions and promises are not allowed. Thunk middleware can solve this problem. The action level is resolved, and the component has no effect. Here I cooperate with react-redux to implement an update operation of redux data.

Second page city search

I implemented a function to search the city and query the weather on the secondary page. Here I use a local json file and use axios to fulfill the request.

 

 

 

axios.get('/city/citys.json').then((res) => 
{   var tem = []      
    tem = res.data.citys.filter((item) => item.citysName.includes(value))      
    if(tem = [])
    {        
        unfound = 'Not Found'      
    }      
    callback(tem.slice(0, 10))      
    loading = false    
})复制代码

 

I use a filter method to perform conditional filtering and return the data containing the input value. If it is empty, a prompt is returned. I use the official component of antd for the search box, which has been encapsulated for us

 

 

 

 <Select  
    showSearch  
    value={this.state.value}  
    placeholder='请输入城市名,快速查询天气信息'  
    defaultActiveFirstOption='flase'  
    showArrow='true'  
    filterOption={false}  
    onSearch={this.handleSearch}  
    onChange={this.handleChange}  
    onBlur={this.handleBlur}  
    notFoundContent={null}  
    style={{ width: '75%' }}  
    bordered='false'  
    loading={loading}  
    notFoundContent={unfound} >   
    {this.state.data.map(d => 
    <Option key={d.id}>{d.citysName}</Option>);} 
</Select>复制代码

 

I use the handleSearch method of the callback function when the text box value of the component changes to implement the interface request and filter the content that meets the search criteria for display. And use the callback function handleChange of the selected options (display bar) to make a change in the state city in redux, and at the same time jump to the home page, code:

 

 

 

handleSearch = value => {    
    if (value) {      
    loading = true      
    fetch(value, data => this.setState({ data }));    
    } 
    else {      
        this.setState({ data: [] });    
    }  
};  
handleBlur = ()  => unfound = null; 
handleChange = value => {    
 this.state.data.map((item) => {      
 if (item.id == value) {        
    let city = item.citysName.split(',')[0]        
    this.props.changeCity(city)        
    this.props.history.push('/')        
    this.setState({ data: [] });      
    }    
})  
};复制代码

Conclusion

Although this project is just a simple small project, it still has some help for your skill tips. In the development process, I also encountered some problems. As the saying goes, the process of solving problems is the process of improving my own abilities. After all, the road to learning is long and the road is long.

For more project details, you can visit my Github , and you are welcome to leave a message and exchange

Published 184 original articles · Like 276 · Visits 160,000+

Guess you like

Origin blog.csdn.net/weixin_38004595/article/details/105183337