Redux

It can be understood as a global data state management tool for component communication and data sharing.

Usage Scenarios:

  1. The state of a component needs to be shared
  2. A state needs to be used in more than one place
  3. One component needs to change the state of another component
  4. A component needs to change global state

In general, when it comes to sharing state, it’s too cumbersome to pass layers through props, so that’s where Redux comes in. Redux consists of three main parts: Action, Reducer, and Store.

Action:

1. Data in the store cannot be directly operated and can only be processed by reducer

2. Action is an object and must have a type argument, which is similar to an enumerated type.

const demoAction = {
    const json = axios.post(url: 'xxx', { dataObj: { id: 'xx'}});// Asynchronous request
    dispatch({ type: 'INSERT_INFO', json}); // Call the reducer through dispatch
    
}
Copy the code

reducer

1. The Reducer is the only place that can operate the store

2. You can use combineReducers({reducer1, reducer2… }) merge multiple reducers to prevent too many states from being managed in one Reducer

const demoReducer = (state, action) = > {
    switch (action.type) {
        case INSERT_INFO:
            return { ...state, dataObj: action.json };
        case TO_DO: {
            return{... state, xxx }; }...default:
            returnstate; }}Copy the code

store

1. Use createStore

Subscribe, Dispatch, and getState methods are provided

const demoStore = createStore(reducer);
store.dispatch(actions.INERT_INFO);
store.subcribe(() = > {
    console.info(store.getState());
})
Copy the code

react-redux

Redux is a library designed to make Redux work better with React. Redux divides components into container components and UI components. Container components handle logic, which is only responsible for display and interaction. There are two cores: Provider and Connect.

Provider

After we include the top-level component with the Provider, all components are under the control of react-Redux, but stores must be placed as arguments in the Provider component.

<Provider store={ store }>
    <App />
</Provider>
Copy the code

connect

This method, as a higher-order component, passes the Store and Dispatch defined in the container component to the UI component.

Connect (mapStatetoProps, mapDispatchToProps)(UI component)Copy the code

redux-saga

In practical application scenarios, an Ajax-like asynchronous request operation will be performed before reducer is called in the action. The reducer operation needs to be performed after receiving the result set of the asynchronous request. Redux-saga handled this gracefully, and asynchronous code was written synchronously to solve the asynchronous problem publicly.

Auxiliary function

takeEvery

If the same action is triggered more than once, it is executed each time. Again, take the redux part of the action code in this article as an example.

const demoAction = {
    // const json = axios.post(url: 'xxx', { dataObj: { id: 'xx' } }); // Asynchronous request
    // dispatch({ type: 'INSERT_INFO', json}); // Call the reducer through dispatch
    function* demoAction() {
        yield* takeEvery('INSERT_INFO', axions.post(url: 'xxx', params)); }}Copy the code

takeLastest

When an action is triggered multiple times, we just want to get the response to the latest request.

const demoAction = {
    // const json = axios.post(url: 'xxx', { dataObj: { id: 'xx' } }); // Asynchronous request
    // dispatch({ type: 'INSERT_INFO', json}); // Call the reducer through dispatch
    function* demoAction() {
        yield* takeLastest('INSERT_INFO', axions.post(url: 'xxx', params)); }}Copy the code

Effect side Effect function

take

Listening for future actions, he creates a command object that tells middleware to wait for a specific action, and the Generator will pause until an action matching pattern is initiated. Take is a blocking effect. (Actually rarely used)

function* demoAction() {
    while (true) {
        yield take('WAIT_MOMENT');
        yieldfork(fetchData); }}Copy the code

put

It can be understood as the dispatch function in REdux, which calls the corresponding method in the Reducer method and updates the state

function* demoAction() {
    yield put({ type: 'INSERT_INFO'.data: list });
}
Copy the code

call

Can be interpreted as a method that calls other functions, usually asynchronously through call

function fetchData() {
    axios.get(url, { data: { ...params } });
}
function* demoAction() {
    const result = yield call(fetchData);
    yield put({ type: 'UPDATE_DATA'.data: { ...result });
}
Copy the code

fork

Similar to call, fork is a non-blocking function that executes the following code immediately after the yield fork(fetchData) is executed, rather than waiting for the fetchData result to return.

function fetchData() {
    axios.get(url, { data: { ...params } });
}
function* demoAction() {
    const result = yield fork(fetchData);
}
Copy the code

select

The Middleware simply calls the provided selector to get data from the store. For example, if we want to call an interface with a userID as a parameter, we can retrieve it from a user that has already been retrieved and stored in a store instead of using the result again

function* demoAction() {
    const ID = yield select(state= > state.user.id);
}
Copy the code

The whole redux, React-redux,redux-saga thing is a bit of a hassle, especially when it comes to writing code during development and creating files. I suggest that you can take a look at the DVA framework when you are free, which encapsulates this whole set and is more conducive to understanding.