redux

Redux is a centralized data warehouse for multiple component data sources, maintaining the same data sample and maintaining consistency among components.

use

  1. Create a store and accept the Reducer parameters
// store/index.js
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from './reducer';
import thunk from 'redux-thunk';
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENTION_COMPOSE__ ?
  window.__REDUX_DEVTOOLS_EXTENTION_COMPOSE__() :
  compose;
const enhancer = composeEnhancers(applyMiddleware(thunk));

const store = createStore(reducer, enhancer);
export default store;
Copy the code

Reducer is to handle the distribution of actions and correctly return to the state manager

import { CHANGE_INPUT, ADD_ITEM, DELETE_ITEM, GET_LIST } from './actionTypes';
const defaultState = {
  inputValue: 'write Something'.list: [Test '1'.'test 2']};export default (state = defaultState, action) => {
  let newState = JSON.parse(JSON.stringify(state));
  console.log(action);
  if (action.type === CHANGE_INPUT) {
    newState.inputValue = action.value;
  } else if (action.type === ADD_ITEM) {
    console.log('456');
    newState.list.push(newState.inputValue);
  } else if (action.type === DELETE_ITEM) {
    newState.list.splice(action.index, 1);
  } else if (action.type === GET_LIST) {
    newState.list = action.data.data;
  }
  return newState;
};
Copy the code

Separate actionType from actionCreators

// store/actionTypes.js
export const CHANGE_INPUT = 'changeInput';
export const ADD_ITEM = 'addItem';
export const DELETE_ITEM = 'deleteItem';
export const GET_LIST = 'getList';
Copy the code
// store/actionCreators.js
import { CHANGE_INPUT, ADD_ITEM, DELETE_ITEM, GET_LIST } from './actionTypes';
import axios from 'axios';
const changeInputAction = value= > ({
  type: CHANGE_INPUT,
  value,
});
const AddItemAction = () = > ({
  type: ADD_ITEM,
});
const DeleteItemAction = index= > ({
  type: DELETE_ITEM,
  index,
});
const getList = data= > ({
  type: GET_LIST,
  data,
});
const getListThunk = () = > dispatch= > {
axios.get('https://www.fastmock.site/mock/dc49e8a7c9c73a80db073480577b1fc4/list/data').then(res= > {
    console.log(res.data);
    const { data } = res;
    const action = getList(data);
    dispatch(action);
  });
};
export { changeInputAction, AddItemAction, DeleteItemAction, getList, getListThunk };
Copy the code

The react – use redux

Stripped of the component’s view and data, the pure UI component used in the Store is stateless, with all the data and methods coming from props

import React, { useEffect } from 'react';
import 'antd/dist/antd.css';
import { Input, Button, List } from 'antd';
import { connect } from 'react-redux';
import { changeInputAction, AddItemAction, DeleteItemAction, getListThunk } from './store/actionCreators';
const TodoList = props= > {
  useEffect(() = >{ props.getList(); } []);return (
    <>
      <div>
        <Input value={props.inputValue} onChange={props.inputChange} style={{ width: '250px', marginRight: '10px' }} />
        <Button onClick={props.addItem}>increase</Button>
      </div>
      <div style={{ width: '300px', margin: '10px' }}>
        <List
          bordered
          dataSource={props.list}
          renderItem={(item, index) = > <List.Item onClick={()= > props.deleteItem(index)}>{item}</List.Item>} / ></div>
      <div />
    </>
  );
};
const mapStateToProps = state= > ({
  inputValue: state.inputValue,
  list: state.list,
});
const mapDispatchToProps = dispatch= > ({
  inputChange(e) {
    let action = changeInputAction(e.target.value);
    dispatch(action);
  },
  addItem() {
    let action = AddItemAction();
    dispatch(action);
  },
  deleteItem(index) {
    let action = DeleteItemAction(index);
    dispatch(action);
  },
  getList() {
    letaction = getListThunk(); dispatch(action); }});export default connect(mapStateToProps, mapDispatchToProps)(TodoList);
Copy the code

When the UI component is used, there will be a provider to provide store in the outer layer. The function of connect is to map the state and dispath of store to the attributes of UI component one by one.

// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';
import { Provider } from 'react-redux';
import store from './store';
const app = (
  <Provider store={store}>
    <TodoList />
  </Provider>
);
ReactDOM.render(app, document.getElementById('root'));
Copy the code

The use of story – thunk

const getList = data= > ({
  type: GET_LIST,
  data,
});
const getListThunk = () = > dispatch= > {
  axios.get('https://www.fastmock.site/mock/dc49e8a7c9c73a80db073480577b1fc4/list/data').then(res= > {
    console.log(res.data);
    const { data } = res;
    const action = getList(data);
    dispatch(action);
  });
};
Copy the code

Previously, redux could only distribute an action as an object. With thunk middleware, it can be a function