1. The directory

  • Story synopsis
  • case
  • React-redux core introduction

2. The story synopsis

  • Redux is part of the React Family bucket, which attempts to provide a “predictable state management” mechanism for react applications.

  • Redux stores the entire application state in one place, called a store

  • I’m going to keep a state tree in there

  • Components can dispatch actions to stores instead of notifying other components directly

  • Other components can refresh their views by subscribing to states in the Store

3. The installation

npm install --save redux
Copy the code

4. Redux of the core

4.1 the State

State is a collection of data

Can be understood as the raw materials that factories need to process goods

4.2 the action

If the State changes, the View changes. But the user doesn’t have access to the State, only to the View so the change in State must be caused by the View.

An action is an instruction that changes state. There are as many actions as there are operations on state.

Can you think of an action as an indicator of what happened

4.3 Reducer machining function

Action puts the state into the Reucer processing function after issuing the command, and returns the new state. You can think of it as a machine for processing

4.4 store

Store can be understood as a total factory with multiple processing machines

let store = createStore(reducers);
Copy the code

A Store is an object that ties them together. The Store has the following responsibilities:

Maintain application state; Provide the getState() method to getState; Provide a dispatch(action) method to update state; Register a listener with subscribe(listener); Unsubscribe the listener via a function returned by subscribe(listener).Copy the code

We can use store.getState() to find out the state of an item in the factory and use store.dispatch to send an action directive.

5. Classic cases

This is a classic case of Redux

  • Define the Reducer function to change state based on the type of action
  • Actions definition directive
  • Create a store using createStore
  • Call store.dispatch() to issue the command to change state
import { createStore } from 'redux'

const reducer = (state = {count: 0}, action) => {
  switch (action.type){
    case 'INCREASE': return {count: state.count + 1};
    case 'DECREASE': return {count: state.count - 1};
    default: return state;
  }
}

const actions = {
  increase: () => ({type: 'INCREASE'}),
  decrease: () => ({type: 'DECREASE'})
}

const store = createStore(reducer);

store.subscribe(() =>
  console.log(store.getState())
);

store.dispatch(actions.increase()) // {count: 1}
store.dispatch(actions.increase()) // {count: 2}
store.dispatch(actions.increase()) // {count: 3}

Copy the code

We could use store.dispatch directly on the React Component, but that would be inconvenient. We need react-redux in this case

class Todos extends Component {
    render(){
        return(
            <div onCLick={()=>store.dispatch(actions.delTodo()) }>test</div>
        )
    }
}
Copy the code

6. react-redux

Redux provides the React binding library. It is efficient and flexible.

6.1 installation

npm install --save react-redux
Copy the code

6.2 the core

  • < Provider store>
  • connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])

Any component within a Provider (such as Comp here) that needs to use data from State must be “connected” — the product of wrapping “your component (MyComp)” with connect.

This function allows us to bind the data in the store to the component as props.

The simple process is shown below:

The Connect method in React-Redux wraps getState and Dispatch on the store as props for the component.

Change the code that was dispatched directly on the component to the following:

index.js

import React, { Component } from 'react'; import store from '.. /store'; import actions from '.. /store/actions/list'; import {connect} from 'react-redux'; class Todos extends Component { render(){ return( <div onCLick={()=>this.props.del_todo() }>test</div> ) } } export default connect( state=>state, actions )(Todos);Copy the code

The Provider takes the key store and passes it to each child component

7. How does Connect work?

Connect () takes four parameters, mapStateToProps, mapDispatchToProps, mergeProps, and options.

7.1 mapStateToProps This function allows us to bind data in a store to components as props.

reducer.js

export default function (state = { lists: [{text:' mobile plan '}],newType:'all'}, action) {switch (action.type) {case types.add_todo: return {... state,lists:[...state.lists,{text:action.text}]} case types.TOGGLE_TODO: return {... state,lists:state.lists.map((item,index)=>{ if(index == action.index){ item.completed = ! item.completed } return item })} case types.DEL_TODO: return {... state,lists:[...state.lists.slice(0,action.index),...state.lists.slice(action.index+1)]} case types.SWITCH_TYPE: console.log({... state,newType:action.newType}) return {... state,newType:action.newType} default: return state; }}Copy the code

In reducer. Js, the initialized state is defined. By using the connect method, we can get the initialized state using this.props. Lists.

import React, { Component } from 'react'; import store from '.. /store'; import actions from '.. /store/actions/list'; import {connect} from 'react-redux'; class Todos extends Component { render(){ return( { + <ul> + this.props.state.lists.map(list =>( + <li>{list.text}</li> + )) + </ul> } <div onCLick={()=>this.props.del_todo() }>test</div> ) } } export default connect( state=>state, actions )(Todos);Copy the code

When state changes, or ownProps changes, mapStateToProps is called, and a new stateProps is computed, which (after merging with ownProps) is updated to MyComp.

7.2 mapDispatchToProps (dispatch, ownProps) : The second parameter to dispatchProps Connect is mapDispatchprops, which binds action as props to MyComp.

action.js

import * as types from ".. /action-types"; export default{ add_todo(text){ return { type: types.ADD_TODO, text: text} }, del_todo(idx){ return {type:types.DEL_TODO, index: idx} }, toggle_todo(index){ return {type:types.TOGGLE_TODO, index} }, del_todo(index){ return {type:types.DEL_TODO, index} }, switch_type(newType){ return {type:types.SWITCH_TYPE, newType} } }Copy the code

The commands I define to change the state in action.js become props bound to the REAC component via connect’s mapDispatchToProps method.

We can easily use to call

    <div onCLick={()=>this.props.del_todo() }>test</div>
Copy the code

8. Deep

Given this, we can see that we didn’t use the store.dispatch method to issue the command, but the state has changed and the view has changed, so what happened?

store.dispatch(actions.increase())
Copy the code

The key is connect()

Connect Principle simplified version

import React,{Component} from 'react'; import {bindActionCreators} from 'redux'; import propTypes from 'prop-types'; export default function(mapStateToProps,mapDispatchToProps){ return function(WrapedComponent){ class ProxyComponent extends Component{ static contextTypes = { store:propTypes.object } constructor(props,context){ super(props,context); this.store = context.store; this.state = mapStateToProps(this.store.getState()); } componentWillMount(){ this.unsubscribe = this.store.subscribe(()=>{ this.setState(mapStateToProps(this.store.getState())); }); } componentWillUnmount(){ this.unsubscribe(); } render(){ let actions= {}; if(typeof mapDispatchToProps == 'function'){ actions = mapDispatchToProps(this.store.disaptch); }else if(typeof mapDispatchToProps == 'object'){ console.log('object', mapDispatchToProps) actions = bindActionCreators(mapDispatchToProps,this.store.dispatch); } return <WrapedComponent {... this.state} {... actions}/> } } return ProxyComponent; }}Copy the code

1. Return state from connect by returning state from a store on the Provided parent component

mapStateToProps(this.store.getState());
Copy the code

Redux’s helper function, bindActionCreators(), listens on each action with Dispatch.

 bindActionCreators(mapDispatchToProps,this.store.dispatch);
Copy the code

To call the method on props, the store.dispach (XXX) event is automatically dispach (XXX)

React-redux simple example project link

Refer to the article

React-redux middleware will continue to be covered in redux middleware articles.

Feel fun to pay attention to ~ welcome everyone to collect comments ~~~

Recruitment is stuck

Bytedance is hiring!

Position Description: Front-end Development (senior) ToB Direction — Video Cloud (Base: Shanghai, Beijing)

1. Responsible for the productization of multimedia services such as voD/live broadcast/real-time communication and the construction of business cloud platform;

2. Responsible for the construction and system development of multimedia quality system, operation and maintenance system;

3, good at abstract design, engineering thinking, focus on interaction, to create the ultimate user experience.

Job requirements

1. Major in Computer, communication and electronic information science is preferred;

2, familiar with all kinds of front end technology, including HTML/CSS/JavaScript/Node. Js, etc.

3. In-depth knowledge of JavaScript language and use of React or vue.js and other mainstream development frameworks;

4. Familiar with Node.js, Express/KOA and other frameworks, experience in developing large server programs is preferred;

5. Have some understanding of user experience, interactive operation and user demand analysis, experience in product or interface design is preferred;

6, own technical products, open source works or active open source community contributors are preferred.

Position window

Relying on the audio and video technology accumulation and basic resources of douyin, Watermelon video and other products, the video Cloud team provides customers with the ultimate one-stop audio and video multimedia services, including audio and video on demand, live broadcasting, real-time communication, picture processing, etc. Internally as the video technology center, service internal business; External to create productized audio and video multimedia service solutions, serving enterprise users.

The team has standardized project iteration process and perfect project role configuration; Strong technical atmosphere, embrace open source community, regular sharing, so that everyone can grow with the rapid business, with technology to change the world!

The delivery way

You can send your resume directly to: [email protected]

You can also scan the push two-dimensional code online delivery, looking forward to your participation! ~