Day 2 steps 7-9 updates

This commit is contained in:
Elizabeth Craig
2019-03-01 12:41:44 -08:00
parent 91ebfb8517
commit 8e4b697ba8
5 changed files with 79 additions and 57 deletions

View File

@@ -47,24 +47,47 @@ const NewComponent = connect(
`connect()` takes in a few functions that map portions of the state tree and dispatcher functions into props. It is a **higher-order function**, meaning that the return value of `connect()` is a function that decorates `OldComponent` into a `NewComponent` with all the mapped props.
A [`mapStateToProps`](https://react-redux.js.org/api/connect#mapstatetoprops-state-ownprops-object) function selects out portions of the state tree. This function informs the connected view when to re-render based on a shallow comparison from previous state.
#### `mapStateToProps`
A [`mapStateToProps`](https://react-redux.js.org/api/connect#mapstatetoprops-state-ownprops-object) function returns portions of the state tree that will be passed to the component as props.
Under the hood, this function helps inform the connected view when it should re-render based on a shallow comparison with the previous state.
```ts
function mapStateToProps(state) {
interface Store {
foo: string;
// and probably some other properties
}
interface FooProps {
foo: string;
bar: string;
}
function mapStateToProps(state: Store): Partial<FooProps> {
return {
foo: state.foo
};
}
```
An optional [`mapDispatchToProps`](https://react-redux.js.org/api/connect#mapdispatchtoprops-object-dispatch-ownprops-object) function will trigger the action message dispatch mechanism of Redux. It looks like this:
#### `mapDispatchToProps`
A [`mapDispatchToProps`](https://react-redux.js.org/api/connect#mapdispatchtoprops-object-dispatch-ownprops-object) function generates props which are used to dispatch Redux actions.
This function generally returns props which the component will use as callbacks in response to user actions.
```ts
function mapDispatchToProps(dispatch) {
interface FooProps {
foo: string;
addTodo: (label: string) => void;
}
function mapDispatchToProps(dispatch: any): Partial<FooProps> {
return {
// the dispatched message COULD be generated by an
// action creator instead
addTodo: () => dispatch({ type: 'addTodo', ... })
// action creator instead (see later steps)
addTodo: (label: string) => dispatch({ type: 'addTodo', label })
}
}
```