Chen Jian's Java Blog 

Redux - avoid to pass props down component tree manually - 4. Build container components more easily with connect()

by Chen Jian


Posted on 2018-06-19 21:30 in Frontend


With connect() you don't have to manually write the container component as a Component class.

 
const CounterComponentContainer = connect(
		// store.state => props of child component. Normally it's extracted as a function called mapStateToProps()
		state => { 
			return {counter: state.counter} 
		}, 
		// store.dispatch => props of child component. Normally it's extracted as a function called mapStateToDispatch()
		dispatch => {
			return {onChange: (amount) => dispatch({type: 'counterChange', amount: amount})} 
		}
) (CounterComponent);    //connect() returns a function.  Here you invoke the returned function with the original component as the parameter.

//And the following is not needed any more. You can comment it out. 
// CounterComponentContainer.contextTypes = {
//		store: PropTypes.object
// };
 

And you can go even futher. You don't have to give the conainer component a name.

CounterComponent = connect(
		
		state => { 
			return {counter: state.counter} 
		}, 
		
		dispatch => {
			return {onChange: (amount) => dispatch({type: 'counterChange', amount: amount})} 
		}
) (CounterComponent);  //CounterComponent will be changed from a reusable component to a container component


class AppComponent extends Component {
  render() {
    return (

      <div className="App">
        ...
        <CounterComponent/>   <!-- This is still a container component -->
        ...
      </div>

    );
  }
}

This is it! Nothing sucks any more!



No one has commented yet.
该日志评论功能被禁用了。