提交 08b14e49 编写于 作者: J Junyoung Choi 提交者: Luis Fernando Alvarez D

Simplify mobx example (#8269)

上级 43370c1f
import App, { Container } from 'next/app'
import React from 'react'
import { initializeStore } from '../store'
import { fetchInitialStoreState, Store } from '../store'
import { Provider } from 'mobx-react'
class MyMobxApp extends App {
static async getInitialProps(appContext) {
// Get or Create the store with `undefined` as initialState
// This allows you to set a custom default initialState
const mobxStore = initializeStore()
// Provide the store to getInitialProps of pages
appContext.ctx.mobxStore = mobxStore
state = {
store: new Store(),
}
let appProps = await App.getInitialProps(appContext)
// Fetching serialized(JSON) store state
static async getInitialProps(appContext) {
const appProps = await App.getInitialProps(appContext)
const initialStoreState = await fetchInitialStoreState()
return {
...appProps,
initialMobxState: mobxStore,
initialStoreState,
}
}
constructor(props) {
super(props)
const isServer = typeof window === 'undefined'
this.mobxStore = isServer
? props.initialMobxState
: initializeStore(props.initialMobxState)
// Hydrate serialized state to store
static getDerivedStateFromProps(props, state) {
state.store.hydrate(props.initialStoreState)
return state
}
render() {
const { Component, pageProps } = this.props
return (
<Container>
<Provider store={this.mobxStore}>
<Provider store={this.state.store}>
<Component {...pageProps} />
</Provider>
</Container>
......
......@@ -4,14 +4,16 @@ import { useStaticRendering } from 'mobx-react'
const isServer = typeof window === 'undefined'
useStaticRendering(isServer)
class Store {
export class Store {
@observable lastUpdate = 0
@observable light = false
constructor(isServer, initialData = {}) {
hydrate(serializedStore) {
this.lastUpdate =
initialData.lastUpdate != null ? initialData.lastUpdate : Date.now()
this.light = !!initialData.light
serializedStore.lastUpdate != null
? serializedStore.lastUpdate
: Date.now()
this.light = !!serializedStore.light
}
@action start = () => {
......@@ -24,15 +26,7 @@ class Store {
stop = () => clearInterval(this.timer)
}
let store = null
export function initializeStore(initialData) {
// Always make a new store if server, otherwise state is shared between requests
if (isServer) {
return new Store(isServer, initialData)
}
if (store === null) {
store = new Store(isServer, initialData)
}
return store
export async function fetchInitialStoreState() {
// You can do anything to fetch initial store state
return {}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册