Git Product home page Git Product logo

umi-plugin-redux-toolkit's Introduction

umi-plugin-redux-toolkit

中文文档

The plugin of umi@4 uses @reduxjs/toolkit.

Install and use

If you want to use plugin, you must install first.

yarn add umi-plugin-redux-toolkit @reduxjs/toolkit
// or
npm install umi-plugin-redux-toolkit @reduxjs/toolkit

Finish installed, you may enable the plugin.

Configuration

  • ignoreOptions { object } : Configure ignored options, refer to
    https://redux-toolkit.js.org/api/serializabilityMiddleware,
    When the object in redux may be created from new Class, or other non-serializable values,
    there will be a warning when the action is obtained or called, and this option can be configured to ignore the warning.

    • ignoreOptions.ignoredPaths { Array<string> } : Ignore value.
    • ignoreOptions.ignoredActions { Array<string> } : Ignored actions.
  • modelName { string } : Customize the name of the model folder and ignore the singular configuration after configuration.

  • singular { boolean } : Whether the directory is singular.

  • esModule { boolean } : Import using the es6 module method.

  • ignore { string | Array } : Ignored model files. (Refer to the ignore configuration of glob)

  • asyncLoadReducers { boolean } : Enable the function of asynchronously injecting reducers.
    (Need to manually mount on the component, it will be more troublesome, so it is not recommended).

How to configure

// .umirc.js or umi.config.js
import { defineConfig } from 'umi';

export default {
  // Configuration of umi-plugin-redux-toolkit
  reduxToolkit: {
    esModule: true
  }
};

How to use

Create the models folder, create a ts or js file under the folder, and export the slice created by createSlice, or the configuration of createSlice.
Export slice Reference, Export the configuration of createSlice Reference.

import { createSlice } from '@redux/toolkit';

const slice = createSlice({
  name: 'sliceName',
  initialState: { value: 0 },
  reducers: {
    addValue(state, action) {
      state.value++;
    }
  }
});

const { addValue } = slice.actions;

export default slice;

When exporting the configuration of createSlice, if the reduce key is created by createAction, the namespace will be automatically removed. E.g:

import { createAction } from '@redux/toolkit';

const action = createAction('sliceName/action');

export default {
  name: 'sliceName',
  initialState: { value: 0 },
  reducers: {
    // will automatically change index/action into action
    [action](state, action) {
      return state;
    }
  }
};

Now also supports exporting APIs created by RTK RTKQuery. E.g:

import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';

const api = createApi({
  reducerPath: 'api',
  baseQuery: fetchBaseQuery({ baseUrl: '/' }),
  endpoints(builder) {
    return {
      getData: builder.query({
        query: (q) => q
      })
    };
  }
});

export const { useGetDataQuery } = api;
export default api;

Exporting listenerMiddleware is now also supported. E.g:

import { createListenerMiddleware } from '@reduxjs/toolkit';
import { setAction } from './actions';

const listenerMiddleware = createListenerMiddleware();

listenerMiddleware.startListening({
  actionCreator: setAction,
  effect(action, listenerApi) {
    console.log('Listener: setAction');
  }
});

export default listenerMiddleware;

Initial value

Export in app.js

export const reduxToolkit = {
  initialState: {},    // Initialize the value of redux
  ignoreOptions: {},   // Same as the ignoreOptions configuration above, it will be merged
  warnAfter: 800,      // If the check time of immutableCheck and serializableCheck exceeds 32ms, there will be a warning. Modify the warning time
  reducers: {},        // Custom add reducers
  middlewares: [],     // Custom add middlewares
  treatStore(store) {} // Allows you to perform other processing on the store, such as mounting some monitoring methods
};

// or

export function reduxToolkit() {
  return {
    initialState: () => ({}), // It can also be a function to initialize the value of redux
    ignoreOptions: {},        // Same as the ignoreOptions configuration above, it will be merged
    warnAfter: 800,           // If the check time of immutableCheck and serializableCheck exceeds 32ms, there will be a warning. Modify the warning time
    reducers: {},             // Custom add reducers
    middlewares: [],          // Custom add middlewares
    treatStore(store) {}      // Allows you to perform other processing on the store, such as mounting some monitoring methods
  };
}

Asynchronous injection of reducers

The *.async.{js,jsx,ts,tsx} files in the models folder will be considered as asynchronously injected reducers and will not be automatically loaded.
Configure asyncLoadReducers: true to enable asynchronous injection of reducers.

Api created by RTK RTKQuery cannot be loaded asynchronously because it needs to add middleware.

import { dynamicReducers } from 'umi-plugin-redux-toolkit/dynamicReducers';
import model_0 from './models/model_0';
import model_1 from './models/model_1';

function Component(props) {
 return <div />;
}

export default dynamicReducers([model_0, model_1])(Component); // Multiple models pass array
// or
export default dynamicReducers(model_0)(Component); // Single model

Get the store object

You can get the store object in the following way:

import { store } from '@@/plugin-reduxToolkit/store';

umi-plugin-redux-toolkit's People

Contributors

duan602728596 avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

umi-plugin-redux-toolkit's Issues

options.ts中生成的model路径在windows下会被转义

生成的options.ts文件中,import model的路径应该生成为
import model_login_0 from 'x:/src/models/login.ts';
目前生成为:import model_login_0 from 'x:\src\models\login.ts';
这个路径会被转义并识别为一个ts文件,报错:This dependency was not found

umi generate tmp时候失败

image

当我使用最新版本的umi 安装本插件时, 安装完了以后在umi generate tmp 阶段会报如下错误:

Cannot read property 'key' of undefined
TypeError: Cannot read property 'key' of undefined
at Object.fn (D:\work\umi-test\node_modules\umi-plugin-redux-toolkit\dist\plugin\index.js:10:41)
at D:\work\umi-test\node_modules@umijs\core\lib\Service\Service.js:549:44
at Generator.next ()
at asyncGeneratorStep (D:\work\umi-test\node_modules@umijs\core\lib\Service\Service.js:110:103)
at _next (D:\work\umi-test\node_modules@umijs\core\lib\Service\Service.js:112:194)
at D:\work\umi-test\node_modules@umijs\core\lib\Service\Service.js:112:364
at new Promise ()
at D:\work\umi-test\node_modules@umijs\core\lib\Service\Service.js:112:97
at D:\work\umi-test\node_modules@umijs\core\lib\Service\Service.js:554:31
at _next3 (eval at create (D:\work\umi-test\node_modules@umijs\deps\compiled\tapable\index.js:1:7845), :17:17)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/add for documentation about this command.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.