concept mapstatetoprop in category react

appears as: mapStateToProps
Redux in Action

This is an excerpt from Manning's book Redux in Action.

Listing 2.11. src/App.js: connecting components
import React, { Component } from 'react'; import { connect } from 'react-redux'; #1 import TasksPage from './components/TasksPage'; class App extends Component { render() { return ( <div className="main-content"> <TasksPage tasks={this.props.tasks} /> #2 </div> ); } } function mapStateToProps(state) { #3 return { tasks: state.tasks #4 } } export default connect(mapStateToProps)(App); #1 Adds connect to the list of imports #2 Tasks will be available via props after connected to the store. #3 The state argument is the entire contents of the Redux store, specifically the result of calling getState on the store instance. #4 The return value of mapStateToProps is passed into the App component as props, which is why render can reference this.props.tasks. !@%STYLE%@! {"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":1,\"ch\":53},{\"line\":1,\"ch\":55}],[{\"line\":22,\"ch\":0},{\"line\":22,\"ch\":2}],[{\"line\":8,\"ch\":53},{\"line\":8,\"ch\":55}],[{\"line\":23,\"ch\":0},{\"line\":23,\"ch\":2}],[{\"line\":14,\"ch\":53},{\"line\":14,\"ch\":55}],[{\"line\":24,\"ch\":0},{\"line\":24,\"ch\":2}],[{\"line\":16,\"ch\":53},{\"line\":16,\"ch\":55}],[{\"line\":25,\"ch\":0},{\"line\":25,\"ch\":2}]]"} !@%STYLE%@!
  • The commands connect and mapStateToProps pass data from Redux into a React component as props.
  • You needed only minimal changes within mapStateToProps, the point of connection between Redux and React, but the getGroupedAndFilteredTasks isn’t functioning correctly in its current state. It still expects the old Redux store with a single tasks property. You need to modify a few of the existing selectors to handle a new store structure. Because you no longer have a single list of actions, you also need to add a new selector to find the right tasks to pass into the UI to render given the currentProjectId. Most noteworthy here is the addition of getTasksByProjectId, which replaces getTasks. The getFilteredTasks requires two input selectors: one to retrieve tasks and one to retrieve the current search term, as shown in the following listing.