Chen Jian's Java Blog 

Redux - avoid to pass props down component tree manually - 3. Use an extra container component to keep the original one reusable

by Chen Jian


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


So a "container" component will be introduced to wrap the original one. The container component will adapt the store structure to "input parameters" the original one needs. Therefore, the original one doesn't need to access store directly and will be reusable again.

//The reusable component, which doesn't access store any more 
class CounterComponent extends Component {
    constructor(props){
        super(props);
    }

    render(){
        return (

            <div>
                <h2>Counter</h2>
                <h3>{this.props.counter.value}</h3>    
                <div>
                    <button onClick={ e => this.props.onChange(1)}>+</button>   
                    <button onClick={ e => this.props.onChange(-1)}>-</button>    
                </div>
            </div>
        );
    }

}

// the container component, which gets data from the store and passes them as props to the reusable one 
class CounterComponentContainer extends Component {

    render(){
    	 return (        		
    			 <CounterComponent 
    			 	counter={this.context.store.getState().counter}
    			 	onChange={(amount) => this.context.store.dispatch({type: 'counterChange', amount: amount})}
    			 />	
    	        );
    }
}

CounterComponentContainer.contextTypes = {
		store: PropTypes.object
};




class AppComponent extends Component {
  render() {
    return (

      <div className="App">
        ...
        <CounterComponentContainer/>   <!-- Now it uses the container component -->
        ...
      </div>

    );
  }
}



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