Catalogue of this series

  • 01 preface
  • 02 Development environment construction
  • 03 Scaffolding creates projects where everything is a component
  • 04 Basic features JSX, Props, State, Lifecycle, Event, and Style
  • Component rendering control
  • 06 Container components, display components
  • 07 Front-end route react-router
  • 08 State management React-Redux
  • 09 Data request fetch
  • 10 Check the attribute type prop-types

Liking is a virtue:)


Today I’m going to go over redux very quickly, and then talk about applicability, and finally just to simplify the official classic Demo Todo, just follow me through.

The target

  • What is a redux
  • When does it apply
  • Create a Redux application
  • Install the debug plug-in

gossip

Redux is a very deep topic. To talk about the standard study route, go to redux.js.org/introductio…

In order to write this article, I read it quietly

Firstly, there are 7 Introduction

Seems to understand something, don’t know

Then Base 6

In fact, Example: Todo List is the most helpful

Getting Started with Redux

That’s a long story

However, this is also the correct posture for learning, and the website is designed more like an academic site than a tutorial for library tools

Good good ~ ridicule finished, start the text!

What is a redux? Can I not use it

This is a very good picture from the Flux website.

Redux is a data management mode. Various actions are initiated on the interface, and then the Dispatcher updates the State to the Store and pushes the new State to the View

All right, so that’s the concept, what’s the Redux

If React is used to implement this interface, the container components at the bottom will deal with the following businesses: user login, barrage, anchor information, video progress, props, tips, IM chat, etc. There are many more and with the iteration of the product, the functions will only increase

The structure is reasonable as we split the components before, but the data management is troublesome. Various business data is pushed into the sub-components, and various business events are returned to the main container component. The possible code structure is as follows

/ / state
this.state = {
  data1:... .data2:... .data3:... , data... n:... }/ / event
function handelEvent1 = {... }function handelEvent2 = {... }function handelEvent3 = {... }function handelEvent.n = {... }// JSX< Main View Component ><The user information data1={this.state.data1} handleEven1={... } handleEven2={... } handleEven... n={... } />
  <The host information>
    <Basic data data... n={... } handleEven... n={... } />
    <Head portrait data... n={... } handleEven... n={... />
    <Focus on data... n={... } handleEven... n={... />
    <The label data... n={... } handleEven... n={... />
    <The heat data... n={... } handleEven... n={... />.</The host information>
  <player .>
    <. />.<player>.<. player/>.</Main view component>
Copy the code

You find that components, parents, children, are completely unmaintainable, and sorting out these relationships is time consuming and error prone

Redux solves this problem by allowing each component to perform its own Action without returning to the parent container

  • Such asReduxThere are two steps in bullet screen business:
    1. Barrage emitting moduleExecute a barrage actionActioncontent{type: 'BARRAGE_SEND', text: 'BARRAGE_SEND'}
    2. Bullet screen rolling componentNew barrage data is updated to the barrage scrolling component

But also not easy to abuse, I saw some simple form operations, actually also set Redux, completely unnecessary, grasp it yourself

Create a redux app

Let’s take a classic example of todo, the original todo, and I’ve got a shortened version here, so here we go

  • Effect of dynamic figure

  • Component structure

Step 1: Write the Action

Operations generated on the interface

let nextTodoId = 0

export const addTodo = text= > ({
  type: 'ADD_TODO'.id: nextTodoId++,
  text
})

export const toggleTodo = id= > ({
  type: 'TOGGLE_TODO',
  id
})
Copy the code
  • Event format
    • typeThe field must be there, indicating what to do
    • typeValue globally unique
    • typeCapitalized definitions
    • Other fields are freely defined

Step 2: Write Reducers

Event response processing. After processing, return the new state

const todos = (state = [], action) = > {
  switch (action.type) {
    case 'ADD_TODO':
      return [
        ...state,
        {
          id: action.id,
          text: action.text,
          completed: false}]case 'TOGGLE_TODO':
      return state.map(
        todo= >todo.id === action.id ? {... todo,completed: !todo.completed} : todo
      )
    default:
      return state
  }
}

export default todos
Copy the code

Step 3: Incorporate Reducers

Use combineReducers to merge all processes

import { combineReducers } from 'redux'
import todos from './todos'

export default combineReducers({
  todos
})
Copy the code

Suppose you have some other business, such as user, cart

import { combineReducers } from 'redux'
import todos from './todos'
import user from './user'
import cart from './cart'

export default combineReducers({
  todos,
  user,
  cart
})
Copy the code

Step 4: Write the componentAddTodo

  • useconnectConnected components
  • usedispatchMethod Dispatch event
import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '.. /redux/actions'

const AddTodo = ({ dispatch }) = > {
  let input

  return (
    <div>
      <form onSubmit={e= >{ e.preventDefault() if (! input.value.trim()) { return } dispatch(addTodo(input.value)) input.value = '' }}><input ref={node= > input = node} />
        <button type="submit">
          Add Todo
        </button>
      </form>
    </div>
  )
}

export default connect()(AddTodo)
Copy the code

Dispatch (addTodo(input.value)) launches Redux to Reducers, and the state is updated

Step 5: Write the componentTodoList

Let’s do a slightly more complicated one

import React from 'react'
import {connect} from 'react-redux'
import {toggleTodo} from '.. /redux/actions'

const Todo = ({onClick, completed, text}) = > (
  <li
    onClick={onClick}
    style={{
      textDecoration: completed ? 'line-through' : 'none'}} >
    {text}
  </li>
)

const TodoList = ({todos, toggleTodo}) = > (
  <ul>
    {todos.map(todo => (
      <Todo key={todo.id} {. todo} onClick={()= > toggleTodo(todo.id)} />
    ))}
  </ul>
)

const mapStateToProps = state => ({
  todos: state.todos
})

const mapDispatchToProps = dispatch => ({
  toggleTodo: id => dispatch(toggleTodo(id))
})

export default connect(mapStateToProps, mapDispatchToProps)(TodoList)

Copy the code

Again, the connect method, which I’ll focus on here

Let’s look at the official definition connect()

  • define
connect([mapStateToProps], [mapDispatchToProps], [mergeProps], [options])
Copy the code
  • parameter
The name of the instructions
mapStateToProps storeThe bindingstate, do update needs to be passed in
mapDispatchToProps Binding dispatch Eventsevent, default if not passeddispatchObject, like the one aboveAddTodocomponent
mergeProps [mergeProps(stateProps, dispatchProps, ownProps): props] (Function):Merge attributes custom, default if you do not pass· Object. Assign, I also empty default
options Some of the options, I don’t really care, just know that there are, okay

[mapStateToProps], [mapDispatchToProps]

Step 6: Container components

import React from 'react'
import AddTodo from './AddTodo'
import TodoList from './TodoList'

const App = (a)= > (
  <div>
    <AddTodo />
    <TodoList />
  </div>
)

export default App
Copy the code

This is simple, juxtaposed

Finally: AdaptationApp

import React, {Component} from 'react'
import {createStore} from 'redux'
import {Provider} from 'react-redux'
import TodoApp from './todos/components/App'
import todoReducer from './todos/redux/reducers'

const store = createStore(todoReducer)

class BaseRedux extends Component {
  render() {
    return (
      <Provider store={store}>
        <TodoApp />
      </Provider>)}}export default BaseRedux
Copy the code
  • Standard code format
    1. createStore(reducers)createstore
    2. ProviderAdapter pressingstoreObject, child nodes are subject toReduxcontrol

A debugging toolRedux DevTools extension

Effect of dynamic figure

1. Install the Chrome plug-in

Open the story – devtools

2. Configure the code

const store = createStore(
  todoReducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
Copy the code

Add window.__redux_devtools_extension__ && window.__redux_devTools_extension__ () to createStore

3. Enable plug-ins

Open the Chrome debugging tool and click the panel Redux

codepen

code

  • reactjs-example / 6-redux.js

reference

  • The story’s official website
  • The flux’s official website
  • Getting Started with Redux video
  • Building React Applications with Idiomatic Redux video
  • Redux Chinese documents
  • Example: Todo List
  • Redux DevTools extension
  • zalmoxisus/redux-devtools-extension