Most web applications give people an interface to interact with and explore data. Thus, a core challenge of building applications is continuously and reliably syncing the data with the user interface. Toggled switches should stay toggled. Checked boxes should stay checked. Pushing the ‘like’ button should change that button to ‘liked’. The right data should be showing at the right time. This all fits into the realm of managing ‘state’.

In simple apps, vanilla javascript or jQuery generally work fine for managing state. But as applications grow in size and complexity, JS/jQuery can turn into spaghetti code . It will become much harder to know which code is affecting which part of the state. This can create bugs for users and suffering for the developers who have to fix those bugs.

JavaScript libraries and frameworks have been evolving quickly to make applications more reliable and easy to debug. This state management problem is getting easier. React and Redux are two libraries (often used together) that have gained a lot of use in the last 2 years. This tutorial will cover the process of converting a jQuery app to React/Redux.

In our prior post about using JQuery and Google Maps to display and filter campgrounds , we learned how to leverage GeoJSON properties to control which markers are displayed on the map, allowing us to see only a subset of campgrounds that meet our criteria.


List Filtering through State Management: Moving from jQuery to React/Redux

While this is a fine way to design front end filtering, we can improve upon it using React and Redux to help us make our implementation more DRY than WET . In this post we will learn how to build a campground filtering interface using React/Redux by exploring how this architecture can improve on our prior JQuery implementation. Here are some benefits of making the switch:

To add a new filter option in our JQuery implementation, we would have to manually add a new filter button to the UI and hook up event handlers. With React/Redux, we can define the filters we want at runtime and let React/Redux handle the UI and event updates for us. By using state we can avoid having to query the DOM or maintain global variables to keep track of what filters are currently in use React will only redraw elements of the UI which have been altered by changes in state, resulting in faster rendering. Using React components, we can compartmentalize different parts of the UI into separate classes, enabling us to easily update and add new components without having to touch the entire codebase.

In this post we will learn how to create the filtering used in this demo app for finding campgrounds near Crater Lake using React, Redux, and react-bootstrap (for simple styling). You can see the complete code on Github .


List Filtering through State Management: Moving from jQuery to React/Redux
The React Components

Lets get started by going over the React components we will use to filter campgrounds. Our top level component, CampFilterList , will create items of type CampFilter from a list of filters passed down via props. Taking a look at CampFilterList.jsx :

render() { return ( <divclassName="row"> <divclassName="col-sm-4">CampgroundFilters:</div> {this.props.filters.map(item => <CampFilterid={item.get('id')} key={item.get('id')} changeFilter={this.props.changeFilter} /> )} </div> )}

For each item in the filters list we create a CampFilter component with the id that will be passed back to the changeFilter method, which we will discuss in the Redux section. Taking a look at the CampFilter component, we can see how the changeFilter method is called on click, and the id sent as its parameter.

render() { return ( <divclassName="col-sm-2"> <inputtype="checkbox" className="toggle" id={this.props.id} defaultChecked={this.props.inuse} onClick={() => this.props.changeFilter(this.props.id)}/> <labelref="text">{this.props.id}</label> </div> ) }

When a filter is checked, the changeFilter method is called back through the store to the reducer, changing the inuse field, resulting in the campgrounds list being filtered. Like the filters the campgrounds components are list/item, but don’t have any user interaction. You can check out the details in CampList.jsx and CampListItem.jsx .

Setting up the Redux store

Now that we have our filtering React components, let’s go over how we will use Redux to manage state and do the campground filtering.

First, we need to define the initial state for our app in index.js :

function set_state(markers) { store.dispatch ({ type: 'SET_STATE', state: { filters: [ {id: 'shower', inuse: false }, {id: 'pets', inuse: false }, {id: 'flush', inuse: false }, {id: 'water', inuse: false } ], campgrounds: campground_list } }) }

In the set_state function we define a list of filters to be used for our app. The “inuse” field will keep track of how the user is filtering items in the UI. We also define a list of campgrounds that we will apply the filters to. The campgrounds are read from a geoJSON file with properties relating back to the filters:

"type": "Feature", "geometry": { "type": "Point", "coordinates": [-122.166149, 42.865508] }, "properties": { "flush": true, "shower": true, "pets": true, "water": true, "description": "Flush toilet, Shower", "title": "Mazama", "image": "mazama.jpg", "url": "http://www.craterlakelodges.com/lodging/mazama-village-campground/", "marker-size": "small"

You can see how the properties map back to the filter IDs, for example, the ‘pets’ property in the geoJSON corresponds to the filter with ID ‘pets’.

The store variable in the set_state function refers to the Redux store, which will handle the state updates for our app. To create a Redux store we need to have a reducer to handle state transition. Let’s add the SET_STATE action to the reducer in reducer.js , enabling us to execute the above code:

exportdefault function(state = Map(), action) { switch (action.type) { case 'SET_STATE': return setState(state, action.state); defaul

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

主题: ReactjQueryJavaJavaScriptGitRY
分页:12
转载请注明
本文标题:List Filtering through State Management: Moving from jQuery to React/Redux
本站链接:http://www.codesec.net/view/520705.html
分享请点击:


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(35)