In the previous development and learning, REdux has been very difficult to use, and then had to use, so I turned to the blog to learn, now officially start

Initialize the project using react-cli, then create a new index.js in SRC

import ReactDOM from 'react-dom';

function App() {
    return (
        <div>app</div>
    )
}

ReactDOM.render(<App />.document.getElementById('root'))
Copy the code

After running the project, Yarn Start can see that the app appears in the browser and is initialized

Create three components, books, Music and User, and introduce the three components in index and display them

  • books, music, user
function Books() {
    return (
        <div>
            <h1>Books</h1>
        </div>)}export default Books;
Copy the code
function User() {
    return (
        <div>
            <h1>User</h1>
        </div>)}export default User;
Copy the code
function Music() {
    return (
        <div>
            <h1>Music</h1>
        </div>)}export default Music;
Copy the code
  • And then introduce it in the app
import Books from "./books/books";
import User from "./user/user";
import Music from "./music/music";

function App() {
    return (
        <div>
            <User />
            <hr>
            <Books />
            <Music />
        </div>
    )
}

ReactDOM.render(<App />, document.getElementById('root'))

Copy the code
  • Let’s see what happens

Create a context file in the SRC directory and import it into your app

import {createContext} from 'react'

const AppContext = createContext(null);

export default AppContext;
Copy the code

Introduce context in index and add initState


import ReactDOM from 'react-dom';
import Books from "./books/books";
import User from "./user/user";
import Music from "./music/music";
import AppContext from "./context/context";

const initState = {
    books: null.music: null.user: null
}

function App() {
    return (
        <div>
            <User />
            <hr/>
            <Books />
            <Music />
        </div>
    )
}

ReactDOM.render(<App />.document.getElementById('root'))

Copy the code

Create a reducers directory under SRC and add user_reducer.js, book_reduc.js, and music_reduc.js


export default {
    getBooks: (state, action) = > {
        return{... state,books: action.books}
    }
}
Copy the code
export default {
    getMusic: (state, action) = > {
        return{... state,music: action.music}
    }
}
Copy the code
export default {
    getUser: (state, action) = > {
        return{... state,user: action.user}
    }
}
Copy the code

Add the Reducer to the index file, create a recuderConfig, and use the context to initialize the reducer

import ReactDOM from 'react-dom';
import Books from "./books/books";
import User from "./user/user";
import Music from "./music/music";
import AppContext from "./context/context";
import bookReducer from "./reducers/book_reducer";
import musicReducer from "./reducers/music_reducer";
import userReducer from "./reducers/user_reducer";
import {useReducer} from "react";

const initState = {
    books: null.music: null.user: null
}

constreducerConfig = { ... bookReducer, ... musicReducer, ... userReducer }const reducer = (state, action) = > {
    const dispatchFn = reducerConfig[action.type];

    if (dispatchFn) {
        const storeState = dispatchFn(state, action);
        return storeState;
    } else {
        throw  new Error('Don't know'); }}function App() {

    const [state, dispatch] = useReducer(reducer, initState);

    return (
        <AppContext.Provider value={{state, dispatch}} >
            <User />
            <hr/>
            <Books />
            <Music />
        </AppContext.Provider>
    )
}

ReactDOM.render(<App />.document.getElementById('root'))
Copy the code

Create a new ajax.js mock request in the SRC directory

/ / false ajax
// After two seconds, return an object based on path
function ajax(path) {
    return new Promise((resolve, reject) = > {
      setTimeout(() = > {
        if (path === "/user") {
          resolve({
            id: 1.name: "Grinning."
          });
        } else if (path === "/books") {
          resolve([
            {
              id: 1.name: "Advanced Programming in JavaScript"
            },
            {
              id: 2.name: "JavaScript is pithy"}]); }else if (path === "/movies") {
          resolve([
            {
              id: 1.name: "Love before the dawn."
            },
            {
              id: 2.name: "The Notebook"}]); }},2000);
    });
  }
  
  export default ajax;
Copy the code

Use Ajax in the User component and render the data

function User() {

    const {state, dispatch} = useContext(AppContext);

    useEffect(() = > {
        ajax('/user').then(res= > dispatch({type: "getUser".user: res}))
    }, [])

    return (
        <div>
            <h1>User</h1>
            <div>{state? .user ? state? .user? .name: 'loading'}</div>
        </div>)}export default User;
Copy the code

Introduced in books and rendered

import AppContext from ".. /context/context";
import ajax from ".. /ajax";
import {useContext, useEffect} from "react";

function Books() {
    const {state, dispatch} = useContext(AppContext);

    useEffect(() = > {
        ajax('/books').then( res= > dispatch({type: 'getBooks'.books: res}))
    }, [])
    return (
        <div>
            <h1>Books</h1>
            <div>{state? .books? .length > 0 ? state? .books? .map( item => (<div>{item.name}</div>)) : 'Loading '}</div>
        </div>)}export default Books;
Copy the code

At this point, you’re done implementing redux with useReduer