-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix(@examples/basic-routes-rematch-old):修复状态管理
- Loading branch information
Showing
1 changed file
with
29 additions
and
36 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,47 +1,40 @@ | ||
import { init, Models } from '@rematch/core'; | ||
import { init, } from '@rematch/core'; | ||
import cookie from 'cookiejs'; | ||
import global from '../models/global'; | ||
import stores, { Store, RootModel, FullModel } from '../models'; | ||
|
||
let storeInit: any = {}; | ||
|
||
let storeInit = init<RootModel, FullModel>({ | ||
models: { | ||
global: global | ||
}, | ||
plugins: [ | ||
{ | ||
createMiddleware: () => () => next => (action) => { | ||
if (typeof window !== 'undefined') { | ||
const token = cookie.get('token'); | ||
if (token) { | ||
cookie.set('token', token, 1); | ||
} | ||
} | ||
// do something here | ||
return next(action); | ||
}, | ||
}, | ||
], | ||
}); | ||
export const store = (): Store => storeInit; | ||
export const createStore = async (initialState = stores.getState() || {}) => { | ||
const promises: Promise<void>[] = []; | ||
|
||
Object.keys(initialState).forEach((name) => { | ||
promises.push(import(`../models/${name}.js`).then((md) => { | ||
const model = md.default || md; | ||
model.state = initialState[name] || {}; | ||
model.name = name; | ||
return model; | ||
})); | ||
}); | ||
|
||
const models = await Promise.all(promises); | ||
|
||
let model: any = { global: global } | ||
|
||
if (models.length > 0) { | ||
model = models | ||
} | ||
|
||
storeInit = init<RootModel, FullModel>({ | ||
models: model, | ||
plugins: [ | ||
{ | ||
createMiddleware: () => () => next => async (action) => { | ||
if (typeof window !== 'undefined') { | ||
const token = cookie.get('token'); | ||
if (token) { | ||
await cookie.set('token', token, 1); | ||
} | ||
} | ||
// do something here | ||
return next(action); | ||
}, | ||
}, | ||
], | ||
if (name !== "loading") { | ||
promises.push(import(`../models/${name}.ts`).then((md) => { | ||
const model = md.default || md; | ||
model.state = initialState[name] || {}; | ||
model.name = name; | ||
return storeInit.addModel({ ...model }); | ||
})); | ||
} | ||
}); | ||
await Promise.all(promises); | ||
return stores; | ||
}; |