Skip to content

Commit

Permalink
fix(createGlobalState): 延后注册的订阅不能获取最新值
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed Jun 30, 2020
1 parent b07d9a2 commit c4a0062
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 1 deletion.
26 changes: 26 additions & 0 deletions src/react/__snapshots__/createGlobalState.test.tsx.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`createGlobalState bug 延后注册的订阅不能获取最新值: 只有 parent 且值为 o 1`] = `
<DocumentFragment>
<div
id="parent"
>
o
</div>
</DocumentFragment>
`;

exports[`createGlobalState bug 延后注册的订阅不能获取最新值: 有 parent 和 child 且值都为 ok 1`] = `
<DocumentFragment>
<div
id="parent"
>
ok
</div>
<div
id="child"
>
ok
</div>
</DocumentFragment>
`;
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import React from 'react'
import { act, renderHook } from '@testing-library/react-hooks'
import { createGlobalState, CreateGlobalStateResult } from './createGlobalState'
import { render } from '@testing-library/react'

describe('createGlobalState', () => {
describe('有初始值', () => {
Expand Down Expand Up @@ -114,4 +116,30 @@ describe('createGlobalState', () => {
.toBe('jj')
})
})

describe('bug', () => {
test('延后注册的订阅不能获取最新值', async () => {
const useGlobalName = createGlobalState('o')

function Child() {
const [name] = useGlobalName()
return <div id='child'>{name}</div>
}

function Parent() {
const [name] = useGlobalName()
return (
<>
<div id='parent'>{name}</div>
{name === 'ok' && <Child />}
</>
)
}

const { asFragment } = render(<Parent />)
expect(asFragment()).toMatchSnapshot('只有 parent 且值为 o')
useGlobalName.setState('ok')
expect(asFragment()).toMatchSnapshot('有 parent 和 child 且值都为 ok')
})
})
})
3 changes: 2 additions & 1 deletion src/react/createGlobalState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,9 @@ export function createGlobalState<S>(
nextGlobalState = (nextGlobalState as any)(currentGlobalState)
}
if (nextGlobalState !== currentGlobalState) {
bus.emit('setGlobalState', nextGlobalState as any, currentGlobalState)
const prevGlobalState = currentGlobalState
currentGlobalState = nextGlobalState as any
bus.emit('setGlobalState', nextGlobalState as any, prevGlobalState)
}
}
const watchGlobalState: (
Expand Down

0 comments on commit c4a0062

Please sign in to comment.