1. Introduction
Immer is an IMmutable library written by mobx authors. The core implementation is using ES6 proxy.
Official website: github.com/immerjs/imm…
2. Simple implementation
How to simulate a super simple produce, the code is as follows:
function produce(state, thunk) {var stateCopy = { ... state }; let copyTarget; stateCopy.a = new Proxy(state.a, {set(target, prop, val) {copyTarget = { ... target }; copyTarget[prop] = val; }}); thunk(stateCopy); stateCopy.a = copyTarget; return stateCopy; }const target = produce(state, (draftState) => {draftState.a.b = 2; }); // Output 1 and 2console.log(state.a.b, target.a.b);Copy the code
Example 3.
1. When using redux, we have trouble changing the reference type. For example, I want to insert a data “3” into obj.a.c.
Var obj = {a: {b: 1, c: [1,2]}}; var newObj = {... obj,a: {... Obj.a,c: [...obj.a.c, 3] // or obj.a.c.ice ().concat(3)}}// If using immerimport produce from 'immer'; var newObj = produce(obj, draft => {draft.a.c.push(3); });Copy the code
How to open and modify.umirc.js in umijs
export default { plugins: [ [ 'umi-plugin-react', { antd: true, dva: { immer: true, }, }, ], ],};
Copy the code
Modify the history.js file in the models directory:
export default { namespace: 'history', state: { a: { b: 1 } }, reducers: { searchVal(state, { payload }) { state.a.b = 10; }, }, effects: { },};
Copy the code
3. Since it uses proxy, if the hierarchy is deeply nested, there may be performance problems. It is recommended that UMiJS not start DVA, but introduce IMmer in the separate Reducer and then modify state.
export default { namespace: 'history', state: { a: { b: 1 } }, reducers: { searchVal(state, { payload }) { state.a.b = 10; }, }, effects: { },};
Copy the code