Usage and summary of Rudex

Keywords: React JSON Javascript

Usage and summary of Rudex

What is Redux

Redux is a popular JavaScript framework that provides a predictable state container (data state management framework) for applications. Redux is based on a simplified version of the Flux framework, a framework developed by Facebook. In the standard MVC framework, data can flow in two directions between UI components and storage, while Redux strictly restricts data flow in one direction.

How Redux works

How to use Redux

Environmental preparation

  1. Install redux
	cnpm install -D redux
  1. File preparation: create a new store folder in the src directory to store all files related to redux.

Create a book record book (Reducer)

  1. Create the reducer.js file in the store folder to store the data.
  2. Create the initial state data to be used in reducer.js, and expose a function that returns state to process the task and return the processing result.
	const defaultState = {
	    defaultValue: "What book do you want to borrow",
	};
	export default (state = defaultState, action) => {
	    return state;
	}

Recruiting a Librarian (store)

  1. Create index.js file in the store folder to realize three-party communication (logbook, user, display screen).
  2. Introduce redux in index.js:
	import { createStore } from "redux"
  1. Create the store in index.js and expose it for external calls.
	const store = createStore();
	export default store;
  1. In index.js, introduce reducer: (the responsibility is equivalent to giving the logbook to the administrator).
	import reducer from "./reducer"
  1. Officially use reducer in index.js: (the responsibility is equivalent to the official handover record book)
	import { createStore } from "redux";
	import reducer from "./reducer";
	const store = createStore(
	    reducer
	);
	export default store;
  1. Add parameters that can be debugged in chrome browser in index.js (debugging requires installing Redux Devtools plug-in)
	import { createStore } from "redux";
	import reducer from "./reducer";
	const store = createStore(
	    reducer
	    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
	);
	export default store;

Book usage display screen (React Component)

  1. Introducing store
	import store from "../store/index";
  1. Get the data stored in redux in the constructor of the component
	constructor(props) {
	  super(props);
	   // Get the data accessed in redux
	   this.state = store.getState();
	}
  1. Simple rendering
	import React, { Component } from 'react';
	import store from "../store/index";
	class ReduxComponent extends Component {
	    constructor(props) {
	        super(props);
	        this.state = store.getState();
	    }
	    render() {
	        return (
	            <button>{this.state.inputValue}</button>
	        );
	    }
	}
	export default ReduxComponent;

Borrower

  1. Create action (the responsibility is equivalent to the borrower selecting the number to borrow on the display screen)
	import React, { Component } from 'react';
	import store from "../store/index";
	class ReduxComponent extends Component {
	    constructor(props) {
	        super(props);
	        this.state = store.getState();
	    }
	    btnClick=(e)=>{
	    	//Create action
	        const action = {
	            type: "btnClick",
	            value: "Salad loving lion"
	        }
	    }
	    render() {
	        return (
	            <button onClick={this.btnClick}>{this.state.inputValue}</button>
	        );
	    }
	}
	export default ReduxComponent;
  1. Transfer action to store (the responsibility is equivalent to the librarian receiving what book the borrower wants to borrow)
	import React, { Component } from 'react';
	import store from "../store/index";
	class ReduxComponent extends Component {
	    constructor(props) {
	        super(props);
	        this.state = store.getState();
	    }
	    btnClick=(e)=>{
	        const action = {
	            type: "btnClick",
	            value: "Salad loving lion"
	        }
	        //action to store
	        store.dispatch(action);
	    }
	    render() {
	        return (
	            <button onClick={this.btnClick}>{this.state.inputValue}</button>
	        );
	    }
	}
	export default ReduxComponent;

At this time, the data before state (the latest book management data of the last time) and action (the book to be lent this time, that is, the work to be done this time) can be obtained in reducer.js.

Record book view data and modify

  1. The reducer.js file processes the data and returns the new data to the store
	const defaultState = {
	    inputValue: "What book do you want to borrow",
	};
	export default (state = defaultState, action) => {
	    console.log(state,action);
	    if (action.type === "btnClick") {
	        // Make a deep copy of the old state
	        const newState = JSON.parse(JSON.stringify(state));
	        // Modify inputValue in reducer
	        newState.inputValue = action.value;
	        // Return to newState
	        return newState;
	    }
	    return state;
	}

The administrator receives data updates to display large screen and borrowing results

  1. store accepts new state
	import React, { Component } from 'react';
	import store from "../store/index";
	class ReduxComponent extends Component {
	    constructor(props) {
	        super(props);
	        this.state = store.getState();
	        // Execute the method in subscribe whenever the data in the store changes
	        store.subscribe(()=>{
	            this.setState(store.getState());
	        });
	    }
	    btnClick=(e)=>{
	        const action = {
	            type: "btnClick",
	            value: "Salad loving lion"
	        }
	        //action to store
	        store.dispatch(action);
	    }
	    render() {
	        return (
	            <button onClick={this.btnClick}>{this.state.inputValue}</button>
	        );
	    }
	}
	export default ReduxComponent;

At this point, the borrowing operation is completely completed.

The complete instance of Redux

src/store/reducer.js (book usage logbook)

const defaultData = {
    NotBorrow: ["How long do you have to sleep", "So you're still here", "Time is still here, you are still here", "Love in time", "Horror hostess"], // Not borrow
    Borrowed: ["Alive", "Float", "Harvard 4:30 a.m", "Luo Sheng men", "How many flowers fall in a dream"] // Borrowed
}
export default (state = defaultData , action) =>{
    console.log(state,action)
    if (action.type === "BorrowSucc"){
        const newState = JSON.parse(JSON.stringify(state));
        newState.NotBorrow.splice(newState.NotBorrow.findIndex(item => item === action.value), 1)
        newState.Borrowed.push(action.value);
        return newState;
    }
    return state;
}

src/store/index.js (Librarian)

import { createStore } from "redux";
import reducer from "./reducer";
const store = createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;

Src / contents / redux_borrowbooks.jsx (operation of book display screen and borrower)

import React, { Component } from 'react';
import store from "../store";
import "./Redux_BorrowBooks.css";
class Redux_BorrowBooks extends Component {
    constructor(props) {
        super(props);
        // Get the data accessed in redux
        this.state = store.getState();
        // Append state
        this.state.InputValue = "";
        // Execute the method in subscribe whenever the data in the store changes
        store.subscribe(()=>{
            this.setState(store.getState());
        });
    }
    InputChange=(e)=>{
        this.setState({
            InputValue:e.target.value
        })
    }
    BorrowSucc=()=>{
        // Create action
        const action = {
            type:"BorrowSucc",
            value:this.state.InputValue
        }
        // Send action
        store.dispatch(action);
    }
    InputSearch=()=>{
    	if(this.state.InputValue == ""){
            alert("Please enter the book you want to borrow");
        }
        if(this.state.NotBorrow.includes(this.state.InputValue)){
            alert("The book you borrowed exists. You have successfully borrowed it");
            this.BorrowSucc();
        }else if(this.state.Borrowed.includes(this.state.InputValue)){
            alert("The book you borrowed has been borrowed. Please check the column of the book not borrowed carefully");
        }else{
            alert("There are no books you borrowed. Please borrow other books");
        }
        this.setState({
            InputValue:""
        })
    }
    render() {
        const {NotBorrow,Borrowed,HistorySearcch,InputValue,status} = this.state;
        return (
            <div className="Redux_Borrow_Books">
                <div className="search">
                    <div className="search-content">
                        <input placeholder="Please enter the name of the book you want to borrow" onChange={this.InputChange} value={InputValue}/>
                        <button onClick={this.InputSearch}>query</button>
                    </div>
                </div>
                <div className="not-borrow">
                    <p className="title">Books not borrowed</p>
                    <ul className="list">
                        {NotBorrow && NotBorrow.length>0 && NotBorrow.map((item,index)=>{
                            return(
                            <li key={index}>{index+1}.{item}</li>
                            )
                        })}
                    </ul>
                </div>
                <div className="borrowed">
                    <p className="title">Books borrowed</p>
                    <ul className="list">
                        {Borrowed && Borrowed.length>0 && Borrowed.map((item,index)=>{
                            return(
                            <li key={index}>{index+1}.{item}</li>
                            )
                        })}
                    </ul>
                </div>
            </div>
        );
    }
}
export default Redux_BorrowBooks;

src/compontents/Redux_BorrowBooks.css

ul {
    list-style: none;
    padding: 0;
    margin: 0;
}
.Redux_Borrow_Books{
    padding: 20px;
}
.title{
    text-align: left;
    font-size: 16px;
    color: skyblue;
    margin: 0;
}
.list li{
    height: 30px;
    line-height: 30px;
    text-align: left;
    padding-left: 20px;
}
.search-content{
    position: relative;
}
.search-content input{
    width: 100%;
    height: 40px;
    line-height: 40px;
    border-radius: 4px;
    border: 1px solid skyblue;
    padding-left: 10px;
}
.search-content button{
    position: absolute;
    right: 0;
    top: 0;
    width: 40px;
    height: 40px;
    line-height: 40px;
    padding: 0;
    background: skyblue;
    border:none;
}
.hide{
    display: none;
}
.show{
    display: block;
}

Table of contents

Final renderings

Published 40 original articles, won praise 1, visited 1012
Private letter follow

Posted by Druid on Thu, 05 Mar 2020 20:25:58 -0800