Quantcast
Channel: Understanding React-Redux and mapStateToProps() - Stack Overflow
Viewing all articles
Browse latest Browse all 11

Answer by Patrick W. McMahon for Understanding React-Redux and mapStateToProps()

$
0
0

This react& redux example is based off Mohamed Mellouki's example.But validates using prettify and linting rules. Note that we define our propsand dispatch methods using PropTypes so that our compiler doesn't scream at us.This example also included some lines of code that had been missing in Mohamed'sexample. To use connect you will need to import it from react-redux. This example also binds the method filterItems this will prevent scope problems in the component. This source code has been auto formatted using JavaScript Prettify.

import React, { Component } from 'react-native';import { connect } from 'react-redux';import PropTypes from 'prop-types';class ItemsContainer extends Component {  constructor(props) {    super(props);    const { items, filters } = props;    this.state = {      items,      filteredItems: filterItems(items, filters),    };    this.filterItems = this.filterItems.bind(this);  }  componentWillReceiveProps(nextProps) {    const { itmes } = this.state;    const { filters } = nextProps;    this.setState({ filteredItems: filterItems(items, filters) });  }  filterItems = (items, filters) => {    /* return filtered list */  };  render() {    return <View>/*display the filtered items */</View>;  }}/*define dispatch methods in propTypes so that they are validated.*/ItemsContainer.propTypes = {  items: PropTypes.array.isRequired,  filters: PropTypes.array.isRequired,  onMyAction: PropTypes.func.isRequired,};/*map state to props*/const mapStateToProps = state => ({  items: state.App.Items.List,  filters: state.App.Items.Filters,});/*connect dispatch to props so that you can call the methods from the active props scope.The defined method `onMyAction` can be called in the scope of the componets props.*/const mapDispatchToProps = dispatch => ({  onMyAction: value => {    dispatch(() => console.log(`${value}`));  },});/* clean way of setting up the connect. */export default connect(mapStateToProps, mapDispatchToProps)(ItemsContainer);

This example code is a good template for a starting place for your component.


Viewing all articles
Browse latest Browse all 11

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>