Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: model state 支持深拷贝 #16

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/node_modules
/lib
/yarn.lock
/.idea
14 changes: 13 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ const log = (model, constitute, count) => {
}
}

// 实现深拷贝的Object.assign
const deepObjectAssign = (target, source) => {
try {
if (source) {
// 对source进行判空,否则JSON.parse操作会报错: Unexpected token u in JSON at position 0
Object.assign(target, JSON.parse(JSON.stringify(source)))
}
} catch (e) {
console.log(e)
}
}

export default function modelExtend(...models) {
const base = { state: {}, subscriptions: {}, effects: {}, reducers: {}, };
const stateCache = [];
Expand All @@ -38,7 +50,7 @@ export default function modelExtend(...models) {
acc.namespace = extend.namespace;
if (typeof extend.state === 'object' && !Array.isArray(extend.state)) {
check(extend.state, stateCache, stateCount)
Object.assign(acc.state, extend.state);
deepObjectAssign(acc.state, extend.state);
} else if ('state' in extend) {
acc.state = extend.state;
}
Expand Down
18 changes: 18 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,24 @@ describe('modelExtend', () => {
assert.strictEqual(res.state.length, 0);
});

it('should deeply merge states when they are objects', () => {
const originalModel = {
state: {
user: {
name: 'Benjy',
}
},
}
const res = modelExtend(originalModel);
originalModel.state.user.name = 'Yuan';

assert.deepEqual(res.state, {
user: {
name: 'Benjy',
}
});
});

it('should log 2 times of state overwritten log', () => {
modelExtend({
state: {
Expand Down