preface


Redux may not be available on your current project, but it doesn’t hurt to be aware that this article will not benefit anyone

concept


What frameworks and tools will we use first?

React

UI framework

Redux

A state management tool that has nothing to do with React. Other UI frameworks can also use Redux

react-redux

Use Redux in React projects

react-thunk

Middleware, role: support asynchronous action

The directory structure


Tips: Directories not related to Redux have been omitted

| | - SRC | - store Redux directory -- actions. Js | -- index. Js | -- reducers. Js | -- state. Js directory | | - components components -- Test. JSX | - App.js project entryCopy the code

The preparatory work


Step 1: Provide default values. Since Redux is used to manage data, the data must have default values, so we put the default values for state in the state.js file

// state.js

// Declare a default value
// Here are two examples
// Synchronize data: pageTitle
// Async data: infoList (future async interface fetch)
export default {
    pageTitle: 'home'.infoList: []}Copy the code

Step 2: Create reducer, which is the data we really need to use in the future, and we put it in the reducers

// reducers.js

// A tool function that organizes multiple reducers and returns a reducer collection
import { combineReducers } from 'redux'
/ / the default value
import defaultState from './state.js'

A reducer is a function
function pageTitle (state = defaultState.pageTitle, action) {
  // Different actions have different processing logic
  switch (action.type) {
    case 'SET_PAGE_TITLE':
      return action.data
    default:
      return state
  }
}

function infoList (state = defaultState.infoList, action) {
  switch (action.type) {
    case 'SET_INFO_LIST':
      return action.data
    default:
      return state
  }
}

// Export all reducer files
export default combineReducers({
    pageTitle,
    infoList
})


Copy the code

Step 3: Create actions. Now that we have created the Reducer, we have no corresponding actions to work with them, so let’s write the actions

// actions.js

// Action is also a function
export function setPageTitle (data) {
  return (dispatch, getState) = > {
    dispatch({ type: 'SET_PAGE_TITLE'.data: data })
  }
}

export function setInfoList (data) {
  return (dispatch, getState) = > {
    // Use fetch to implement asynchronous requests
    window.fetch('/api/getInfoList', {
        method: 'GET'.headers: {
            'Content-Type': 'application/json'
        }
    }).then(res= > {
        return res.json()
    }).then(data= > {
        let { code, data } = data
        if (code === 0) {
            dispatch({ type: 'SET_INFO_LIST'.data: data })
        }
    })
  }
}
Copy the code

Last step: Create a Store instance

// index.js

// applyMiddleware: Redux uses this function to use middleware
// createStore: used to createStore instances
import { applyMiddleware, createStore } from 'redux'

// Middleware, function: if we do not use this middleware, when we dispatch an action, we need to pass the Action object to the Dispatch function; But if we use this middleware, we can pass in a function that takes two arguments: Dispatch and getState. This dispatch can be used after a future asynchronous request has completed and is useful for asynchronous actions
import thunk from 'redux-thunk'

/ / into the reducer
import reducers from './reducers.js'

// Create a store instance
let store = createStore(
  reducers,
  applyMiddleware(thunk)
)

export default store
Copy the code

Now that we’ve completed all the preparations to use Redux, we’re ready to use Redux in the React component

Begin to use


First, let’s write the entry file app.js for the application


import React from 'react'
import ReactDOM from 'react-dom'

// Import components
import TestComponent from './components/Test.jsx'

// Provider is one of the two core tools for react-Redux. It is used to pass stores to components in each project
// The second tool is connect, which will be described later
import { Provider } from 'react-redux'
// Import the created store instance
import store from '@/store/index.js'

/ / rendering DOM
ReactDOM.render (
  (
    <div>{/* Pass store as prop to make all components of the application use Store */}<Provider store = {store}>
          <TestComponent />
        </Provider>
    </div>
  ),
  document.getElementById('root'))Copy the code

Finally, there is our component: test.jsx

// Test.jsx

import React, { Component } from 'react'

// The connect method is used to pass additional props to the component and return the new component without the component being affected in the process
import { connect } from 'react-redux'

/ / into the action
import { setPageTitle, setInfoList } from '.. /store/actions.js'

class Test extends Component {
  constructor(props) {
    super(props)
  }

  componentDidMount () {
    let { setPageTitle, setInfoList } = this.props
    
    // Trigger the setPageTitle action
    setPageTitle('New title')
    
    // Trigger setInfoList action
    setInfoList()
  }

  render () {
    // Deconstruct the store from props
    let { pageTitle, infoList } = this.props
    
    / / use the store
    return (
      <div>
        <h1>{pageTitle}</h1>
        {
            infoList.length > 0 ? (
                <ul>
                    {
                        infoList.map((item, index) => {
                            <li>{item.data}</li>})}</ul>
            ):null
        }
      </div>)}}// mapStateToProps: Map state to the components props
const mapStateToProps = (state) = > {
  return {
    pageTitle: state.pageTitle,
    infoList: state.infoList
  }
}

// mapDispatchToProps: Maps dispatches to components props
const mapDispatchToProps = (dispatch, ownProps) = > {
  return {
    setPageTitle (data) {
        // If you don't understand the logic, see the introduction of redux-thunk
        dispatch(setPageTitle(data))
        // setPageTitle returns a function
        // This is where redux-thunk comes in: asynchronous actions
        // The uplink code is equivalent to
        /*dispatch((dispatch, getState) => { dispatch({ type: 'SET_PAGE_TITLE', data: data }) )*/
    },
    setInfoList (data) {
        dispatch(setInfoList(data))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(Test)
Copy the code

Redux’s Three principles


  • Single data source The state of the entire application is stored in an object tree that exists in only one store
  • State is read-only and the only way to change State is to trigger an action, which is a generic object that describes events that have occurred
  • To describe how an action changes the State Tree, you need to write reducers, right

conclusion


Use Redux in the React project. Use Redux in the React project. Use Redux in the React project

reference


  • Redux Chinese document

How to use Redux gracefully in React projects