node. JS Learning React,redux,react-redux

Source: Internet
Author: User

Redux very difficult to understand, finally understand a little, do a small demo, record.

First look at the directory structure:

Src

|--index.js

|--actions

|--index.js

|--components

|--additem.js

|--app.js

|--itemlist.js

|--reducers

|--index.js

Final effect

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/7D/55/wKioL1bmYvmCVI9BAAAS3dfD9V8501.png "style=" float: none; "title=" Initial state "alt=" Wkiol1bmyvmcvi9baaas3dfd9v8501.png "/>

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/7D/57/wKiom1bmYnLRPorxAAAc9lYsA64275.png "style=" float: none; "title=" Add Record "alt=" Wkiom1bmynlrporxaaac9lysa64275.png "/>

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/7D/57/wKiom1bmYnOiEYK7AAAZBCs4Q4Y173.png "style=" float: none; "title=" Delete Record "alt=" Wkiom1bmynoieyk7aaazbcs4q4y173.png "/>

Redux Big Three: Actions, reducers, store,

Actionis to use the data from the application (the translator Note: This is not called view because the data may be the server response, user input or other non-view data) to the store payload. It is the store dataonlysources. In general, you will passstore.dispatch()upload the action to the store.


This is an official explanation, and my personal understanding is that action is about defining an event, but not doing anything logically, just binding the data and events you need to work with, and then waiting for the store to distribute it, i.e. update the store. It's like defining a click event for a button;

Btn.addeventlistener (Mouseevent.click,onclickhandle);

This code actually does nothing, just tells the system what to do when it has mouseevent.click messages.


Reducer The Action simply describes the fact that something has happened and does not indicate how the app updates the state. And that's exactly what reducer is going to do.


This is an official explanation, and my understanding is that, like the Onclickhandle function above, the code to be executed when the event is triggered, when the action is dispatched, the store will find the function to execute according to the definition, and then change the store, This causes the react to be re-rendered, eventually changing the view.


The Store is the object that links the action with the reducer. The Store has the following responsibilities:

  • Maintain the state of the application;

  • Provides a getState() way to obtain state;

  • Provides dispatch(action) methods to update state;

  • By subscribe(listener) registering the listener.

Redux app has only one single store. When you need to split the logic of processing data, use the reducer combination instead of creating more than one store.

My understanding is that the store is an event listener plus an event dispatcher plus a status recorder. He will find the corresponding reducer based on the action being triggered.


When I write this demo, I define the action, which is what will be done, and then write the reducer according to these actions, that is, how each event should be handled. Finally wrote the interface, of course, you can also write the interface, according to the interface definition action.

Here's a look at how the code is written, very simple and very primitive code,

Src/actions/index.js:

"Use strict"; Export const Add_item = ' Add_item '; export const Del_item = ' delete_item '; export function AddItem (text) {Retu RN {type:add_item, text}}export function Delitem (index) {return {type:del_item, index}}


This defines two events, one to add records, one to delete records, and one for each method to return an object, which must have a type attribute, which is actually the real event differentiator.

Then the text in AddItem is the content to add the record to, and index is the citation to delete the record. Here, the action is done.

Reducers/index.js:

"Use strict"; import {combinereducers} from ' redux '; import {add_item, del_item} from '. /actions/index '; Const Initalstate = {items:[]};function Aitems (state=[],action) {switch (action.type) {case ADD_ITEM    : Return State.concat ([Action.text]);      Case DEL_ITEM:state.splice (action.index,1);    return [... state];  Default:return State; }}let todos=combinereducers ({items:aitems}); export default Todos;



The content of this file is based on action, by type to distinguish what happened, when a record should be added, the text content is saved in the array and returned,

Here are a few things to note:

1,initalstate{} initial state, which has a property items, array type, of course, can be called other names.

2,aitems's first argument state=[], why would you let state assign an array type? Shouldn't it be an object? This is because in assigning to Todos the sentence, items:aitems, I understand this point is when the trigger event, Redux will automatically traverse Todos, and then the state and Combinereducers in the object to compare, encountered the same name property, Pass the same name attribute value in state to the function corresponding to the property of the same name in Combinereducers, a bit around!!!!

The second parameter of the 3,aitems action, you're right, is the object that we have just returned from the method in the src/actions/index.js we defined.

4,combinereducers function is a very personality function, not much to say.


Src/index.js:

"Use strict", import React from ' React ', import {render} from ' React-dom ', import {createstore} from ' redux '; import {Pro Vider} from ' React-redux ', import App from './components/app ', import todos from './reducers/index '; let store = Createstor E (Todos); let element = document.getElementById (' app '); render (<provider store={store}> <app/> </pro Vider>, Element);



This is not much to say, because each of the articles about react and Redux will have this section, mainly to the react and redux through the React-redux link up.

Look at the components below:

Src/components/app.js:

"Use strict";import react from  ' React ';import {connect } from  ' React-redux ';import { bindactioncreators } from  ' redux '; import  * as  actions from  '. /actions/index ';import additem from  './additem ';import itemlist from  './ItemList '; Class app extends react.component{  render () {    console.log (" App ");    return <div>      <additem  onaddclick={(text)  => this.props.actions.additem (text)} />       <itemlist items={this.props.items} ondelclick={index=>this.props.actions.delitem (Index)} />      </div>  }}export default connect (({items}) = > ({items}), (Dispatch)  =>  ({actions:bindactioncreators (Actions,dispatch)})) (APP);


The code is simple, one can see that the only complication is the last sentence:


Export default Connect (({items}) = ({items}), (dispatch) = ({actions:bindactioncreators (Actions,dispatch)})) ( APP);


Connect receives two objects, the first object is the state in the store, or it can be part of the props property that binds to the view, the second object is the actions, and it becomes the props property of the current view. This allows you to directly invoke the actions of the same name and automatically distribute the corresponding events. When the Connect function returns a function and then passes the current view in, the current view,state,action can be bound together so that the state's data and dispatch events are used in the current view.


Then there are two other components:

Src/components/additem.js:

"Use strict", import React from ' React '; export default class AddItem extends react.component{static proptypes = {Onad  DClick:React.PropTypes.func};    _clickhandle (e) {console.log ("Additemclick");  This.props.onAddClick (This.refs.itemText.value.trim ());    } render () {Console.log ("AddItem"); return <div> <input type= "text" ref= "Itemtext"/><br/> <button Onclick={this._clickhandl E.bind (This)}>add</button> </div>}}


This is the normal react component, which takes some parameters from the parent to use, or receives some functions to implement the function that calls the parent component in the child component.

Src/components/itemlist.js:

"Use strict";import react from  ' React ';export default class itemlist  Extends react.component{  static proptypes={    items: react.proptypes.array.isrequired,    ondelclick:react.proptypes.func  };   _ondelclick (Index) {    console.log ("Itemlistclick", index);     This.props.onDelClick (index);   }  render () {    console.log ("itemlist") ;     console.log (This.props.items);    return <ul>       {        this.props.items.map (Value, Index)  =>          <li>{index},{value}< Button onclick={this._ondelclick.bind (This,index)}>del</button></li>           )}    </ul>  }} 


This, ibid., no more explanations.

Well. Demo here, the main code is finished, and then to comb it again:

1,src/index.js all the packages together.

2, define actions, define reducers.

3, bind state and actions to app.js.

4, the state and actions are passed into sub-components from App.js respectively.

5, if there is an action in the subassembly, the actions are called.

The 6,actions is triggered and the store calls the corresponding reducers.

7,reducers is called to modify state.

8,react detects that state is modified, re-renders the component, and changes views.

Well. It's a step closer.

Reference: http://camsong.github.io/redux-in-chinese/docs/basics/ExampleTodoList.html

This article is from "__ No acted" blog, please make sure to keep this source http://wuzishu.blog.51cto.com/6826059/1750929

node. JS Learning React,redux,react-redux

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.