13React-Redux Usage

Source: HTTP: //www.ruanyifeng.com/blog/2016/09/redux_tutorial_part_three_react-redux.html 
Import Store => onclick => dispatch event => = execute the reducer> store.subscribe
React-Redux components: UI components (responsible for UI rendering) and container components (responsible for managing the data and logic).
React-Redux source of connect:
var connect = createConnect()=>
function createConnect() {
    connectHOC=connectAdvanced
    return function connect(mapStateToProps, mapDispatchToProps, mergeProps) {
        return connectHOC()=>return connectAdvanced()=>function connectAdvanced(selectorFactory) {
            return function wrapWithConnect(WrappedComponent) {
                return hoistNonReactStatics(Connect, WrappedComponent)=>var hoistNonReactStatics = createCommonjsModule(function (module, exports) {
                })
            })
        }
   }
}
A, UI components 
1, UI component has the following characteristics.
(1) is only responsible for rendering UI, without any business logic
(2) is not a state (i.e., without using the variable this.state)
(3) All data by parameters (this.props) provided
(4) do not use any the API Redux
example (6) is below a UI component.
const Title = value => <h1>{value}</h1>;
2, because they do not contain state, UI components, also known as "pure component", that is, it functions like a pure, pure determine its value by the parameter. 

Second, the container assembly
1, the container assembly has the following features.
(1) is responsible for managing data and business logic, not responsible for the UI presentation
(2) with internal state
(3) using the API Redux

three, UI components, and in conjunction with the container assembly
1, if a UI component both have business logic , then it is split into two layers: a container assembly is outside, inside the package of a UI component. The former responsible for communication with the outside, the data to the latter, to render a view of the latter.
2, React-Redux specified, all of the UI components provided by the user, the container assembly is generated automatically by React-Redux.

Four, connect ()
React provided Redux-connect method for generating a UI component from the container assembly.
import { connect } from 'react-redux'
const myContainerComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(myUIComponent)
The above code, myUIComponent a UI component, myContainerComponent is generated automatically by the React-Redux connect method by container assembly. The connect method takes two parameters: mapStateToProps and mapDispatchToProps, which defines the business logic UI components. The former is responsible for input logic, i.e. mapped to external data state attribute UI component (The props); which is responsible for outputting logic, the user is about to operate the UI component mapped into Action objects, spread out from the UI components. 

Five, mapStateToProps ()
. 1, is a function mapStateToProps. Its role is to create a mapping from the object to the state outside the object UI assembly props, returns after executing an object {prop1: state.state1, prop2: state.state2 }.
2, connect let mapStateToProps Subscribe Store, that is the former into the latter's property array, listeners find state update, the implementation of "publishing functions", and then loop through the array and perform; recalculate parameters UI components, thereby triggering re-rendering UI components. Note: Subscribe to as "binding", connect execution triggered subscribe to perform.
3, the first parameter is always mapStateToProps state objects, the second parameter may be used ownProps, representative of props object container assembly. After use, the container assembly if the parameter is changed, will lead to re-render the UI components.
mapStateToProps = const (State, ownProps) => { 
  return { 
    Active: ownProps.filter === state.showFilter 
  // Active: state.active, this case no second parameter ownProps 
  } 
} 
4, if omitted mapStateToProps connect method parameters, then the UI components will not subscribe to Store, Store updates do not cause that is updated UI components. 

Six, mapDispatchToProps ()
. 1, mapDispatchToProps connect function is the second parameter, the parameters used to build the UI component store.dispatch mapping method. In other words, it defines what actions should be passed as the Action Store. I.e., the user operates the component mapped to the action. It can be a function, it can be a target.
2, if a function is mapDispatchToProps, dispatch and will be ownProps (props object container assembly) two parameters. The code can be seen below, mapDispatchToProps as a function, must return an object, "each" key is a map of the object, define how UI component parameters sent Action.
mapDispatchToProps = const (dispatch, ownProps) => { 
  return { 
    event // trigger UI components such as onClick, execute the function myClick, in pure function, the action.type according to the state (filter) assignment, page refresh. 
    MyClick: () => { 
      dispatch ({ 
        type: 'myFilter', 
        filter: ownProps.filter // Get the object from the attribute 
      }); 
    } 
  }; 
} 
3, if mapDispatchToProps is an object, it is corresponding to the same name as the name of each key parameters UI component should be a function key, will be treated as Creator Action, Action will be issued automatically returned by the Redux.
{mapDispatchToProps = const 
  MyClick: (filter) => {// the attribute as a parameter 
    type: 'myFilter', 
    filter: filter 
  }; 
}
 

Seven, <Provider> components
connect method after generation container components, container components need to get the state objects to generate parameter UI components. One solution is to state the object as a parameter passed in the container assembly. But in a deep container components may be level, a state level will pass on very troublesome. React-Redux provide Provider component that allows the container assembly to get state. In the following code, the outside layer of Provider Root Package, all subcomponents are App can get a state.
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import myApp from './reducers'
import App from './components/App'
let store = createStore(myApp);
render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('rootElement')
)
Its principle is the context property React assembly, store in the above context object context. Source as follows:
class Provider extends Component {
  getChildContext() {
    return {
      store: this.props.store
    };
  }
  render() {
    return this.props.children;
  }
}
Provider.childContextTypes = {
  store: React.PropTypes.object
}
Code React-Redux container assembly is automatically generated, so that it is similar to the following, and then store the subassembly can get from the context, the code is as follows.
class myContainerComponent extends Component {
  componentDidMount() {
    const { store } = this.context;
    this.unsubscribe = store.subscribe(() =>
      this.forceUpdate()
    );
  }
  render() {
    const props = this.props;
    const { store } = this.context;
    const state = store.getState();
    // ...
  }
}
myContainerComponent.contextTypes = {
  store: React.PropTypes.object
}

  

VII Example: counter 
1, the following example is a counter component is a pure UI component. This UI component has two parameters: value and onIncreaseClick. The former needs to be calculated from the state, the latter need to issue outwardly Action.
class Counter extends Component {
  render() {
    const { value, onIncreaseClick } = this.props
    return (
      <div>
        <span>{value}</span>
        <button onClick={onIncreaseClick}>Increase</button>
      </div>
    )
  }
}
2, the following definitions state value to a mapping, and to dispatch onIncreaseClick mapping.
mapStateToProps function (State) { 
  return { 
    value: state.count / * may be performed where the results of the function * / 
  } 
} 
function mapDispatchToProps (dispatch) { 
    return { 
            event trigger // UI components such as onclick, execute the function onIncreaseClick, in in pure function, according to the relevant state action.type different assignment, page refresh 
            onIncreaseClick: () => dispatch ( action) / * argument can be an object type {: 'Increase'} * / 
   } 
}
3, the behavior generator (Action Creator)
const action = { type: 'increase' }
4, connect method generating vessel assembly.
const App = connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter)
5, Reducer (pure function) defined in the component.
function counter(state = { count: 0 }, action) {
  const count = state.count
  switch (action.type) {
    case 'increase':
      return { count: count + 1 }
    default:
      return state
  }
}
6, to generate an object store, outside the root layer Package Provider.
import { loadState, saveState } from './localStorage';
const persistedState = loadState();
const store = createStore(
  myApp,
  persistedState
);
store.subscribe(throttle(() => {
  saveState({
    todos: store.getState().todos,
  })
}, 1000))

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('rootElement')
);
Nine, React-Router routing library. Use React-Router project, also wrapped in a layer on the outside with a Provider Router, after all, the only function is to pass Provider store objects.
const Root = ({ store }) => (
  <Provider store={store}>
    <Router>
      <Route path="/" component={App} />
    </Router>
  </Provider>
);
Ten, the difference between HTML and REACT event event 
REACT event with HTML event, the first letter after the incident on REACT is capitalized! For example REACT click event is <button onClick = {myClick}> Click </ button>, and a click event is the HTML <button onclick = "myClick () "> Click </ button>.

Note: Feed - release mode:
1, increasing to a DOM object custom event attributes: obj.selfEvent = [];
2, define a subscription (bound) function, a plurality of custom function, a release function
3, a plurality of times Subscribe to execute (bind) function, the more custom functions into (1) of the array
4, execution publishing functions, find the custom event properties, traversing the array to perform custom functions
in short, in every place Executive "subscription (binding) function", the (custom) function into an array of DOM object properties, waiting for the right time with the "release function" traverse execution.
Another: flux is only a one-way data flow thought, it is not a specific frame.

 

 

 

 

 

  

 

 

 




  

Guess you like

Origin www.cnblogs.com/gushixianqiancheng/p/10964065.html