[Redux] Generating Containers with Connect () from React Redux (Addtodo)

Source: Internet
Author: User

Code to be refacted:

Const ADDTODO = (props, {store}) = = {let  input  ; return (    <div>      <input ref={node = {        = node;       />      <button onclick={() = {        store.dispatch ({          ' Add_todo ',          ID: Nexttodoid+ +,          text:input.value        }        )= ';      }} >        Add Todo      </button>    </div>  = {  Store: React.PropTypes.object};

Instead of passing:

Const ADDTODO = (props, {store}) = = {

We can only pass ' props ', and we get ' dispatch ' from the props:

Let Addtodo = ({dispatch}) = = {

Then we'll create a container component with connect so would inject that the dispatch function as a prop, we'll Remove the context types because the component generated by Connect function would take care of reading this chore from the Context.

The first argument to the Connect function was map straight to props, but there aren ' t any props for at to-do component tha T depend on the current state, so I return an empty object. The second argument to connect are map dispatch to props, but at to-do component doesn ' t need any callback props. It just accepts the dispatch function itself, so I ' m returning it as a prop with the same name.

Finally, I ' m calling the function for a second time to specify the component I want to wrap, in this case, Addtodo itself:

Addtodo = Connect (      + = = {return  {};  }  ,+ = {     return {dispatch};  }) (Addtodo);

However, it is wasteful to even subscribe to this chore if we don ' t calculate any props from the its state. So I ' m replacing the mapstatetoprops function with a null, which tells Connect that there is N o need to subscribeto the This store.

Additionally, it ' s pretty common pattern to inject just the dispatch function. specify NULL or any false value in Connect as the second argument, you ' re going to get dis Patch injected as a prop.

Addtodo = Connect (  null,  null) (Addtodo);

In fact, I can just remove all arguments here. The default behavior would be is to not subscribe to this chore and to inject just the dispatch function as a prop.:

Addtodo = Connect () (Addtodo);

The Addtodo function would looks like:

Let Addtodo = ({dispatch}) + = {let  input  ; return (    <div>      <input ref={node = {        = node;       />      <button onclick={() = {        dispatch ({          ' Add_todo ',          id:nexttodoid + +,          text:input.value        }        )= ';      }} >        Add Todo      </button>    </div>  = Connect () (Addtodo);

The Addtodo component that I declare accepts dispatch as a prop, but it doesn ' t know what the get this store. It just hopes that someone was going to pass the dispatch to it.

The Connect code without any arguments are going to generate a container component that does isn't subscribe to this store. However, that'll pass dispatch to the component that it wraps. In this case, it wraps my Addtodo component.

The second connect call returns the generated container component. I ' m assigning it to Addtodo. I ' m reassigning the Let binding the second time.

------------------

Code:

Const TODO = (state, action) = = {  Switch(action.type) { Case' Add_todo ':      return{id:action.id, text:action.text, completed:false      };  Case' Toggle_todo ':      if(State.id!==action.id) {returnState ; }      return{... state, completed:!state.completed}; default:      returnState ; }};const Todos= (state = [], action) = = {  Switch(action.type) { Case' Add_todo ':      return[... state, Todo (undefined, action)];  Case' Toggle_todo ':      returnState.map (t =Todo (T, action)); default:      returnState ; }};const Visibilityfilter=( State= ' Show_all ', Action)= {  Switch(action.type) { Case' Set_visibility_filter ':      returnAction.filter; default:      returnState ; }};const {combinereducers}=Redux;const Todoapp=combinereducers ({todos, visibilityfilter}); const {Component}=React;const Link=({active, Children, OnClick})= {  if(active) {return<span>{children}</span>;  }  return (    <a href= ' # 'OnClick={e ={e.preventdefault ();       OnClick (); }}    >{Children}</a>  );}; Class Filterlink extends Component {componentdidmount () {const {store}= This. Context;  This. Unsubscribe = Store.subscribe (() = This. ForceUpdate ()); } componentwillunmount () { This. Unsubscribe (); } render () {Const props= This. Props; const {STORE}= This. Context; Const State=store.getstate (); return (      <Link Active={Props.filter===State.visibilityfilter} onClick={() =Store.dispatch ({type:' Set_visibility_filter ', Filter:props.filter}) }      >{Props.children}</Link>    ); }}filterlink.contexttypes={store:react.proptypes.object};const Footer= () + = (  <p>Show: {‘ ‘}    <filterlink filter= ' Show_all ' > All</FilterLink> {', '}    <filterlink filter= ' show_active ' >Active</FilterLink> {', '}    <filterlink filter= ' show_completed ' >completed</FilterLink> </p>); Const Todo=({onClick, completed, text})= (  <Li OnClick={OnClick} style={{textdecoration:completed? ' Line-through ' :          ' None '    }}  >{text}</li>); Const ToDoList=({todos, ontodoclick})= (  <ul>{todos.map (Todo= <Todo Key={todo.id} {... todo} onClick={() =Ontodoclick (todo.id)}/>    )}  </ul>); const {Connect}=Reactredux;let nexttodoid= 0; let Addtodo= ({dispatch}) = ={let input; return (    <div> <input Ref={node ={input=node; }} /> <button onclick={() ={Dispatch ({type:' Add_todo ', Id:nexttodoid++, Text:input.value}) Input.value= ' '; }}>ADD Todo</button> </div>  );}; Addtodo=Connect () (Addtodo); Const Getvisibletodos=(todos, filter)= {  Switch(filter) { Case' Show_all ':      returnTodos;  Case' Show_completed ':      returnTodos.filter (t=t.completed);  Case' Show_active ':      returnTodos.filter (t= =!t.completed); }}const Mapstatetotodolistprops= (state) = = {  return{Todos:getvisibletodos (State.todos, State.visibilityfilter)};}; Const Mapdispatchtotodolistprops= (dispatch) = = {  return{ontodoclick: (ID)={Dispatch ({type:' Toggle_todo ', id}); }  };}; Const Visibletodolist=Connect (Mapstatetotodolistprops, Mapdispatchtotodolistprops) (todolist); Const Todoapp= () + = (  <div> <addtodo/> <visibletodolist/> <footer/> </div>); const {Provider}=reactredux;const {CreateStore}=Redux; Reactdom.render (<provider Store={createstore (todoapp)}> <todoapp/> </provider>, document.getElementById (' root '));

[Redux] Generating Containers with Connect () from React Redux (Addtodo)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.