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> { => <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={} defaultChecked={this.props.inuse} onClick={() => this.props.changeFilter(}/> <labelref="text">{}</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": "", "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
本文标题:List Filtering through State Management: Moving from jQuery to React/Redux

技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(18)