提交 5d8ae445 编写于 作者: T tylim 提交者: Tim Neutkens

improve with-unstated example (#5998)

improve the example so that it can preserve unstated from server to client unstated
上级 ba95f754
......@@ -2,7 +2,7 @@ import * as React from 'react'
import Link from 'next/link'
export default class About extends React.Component {
state = { name: '' };
state = { name: '' }
async componentDidMount () {
const name = await window.getName()
......
......@@ -43,5 +43,4 @@ now
This example shows how to integrate Unstated in Next.js. For more info about Unstated you can visit [here](https://github.com/jamiebuilds/unstated). The example is basically same as [redux example](https://github.com/zeit/next.js/tree/canary/examples/with-redux).
This example also shows how to share state within different page, you can expect the same state for Counter when switching between Index and About.
The "counter" shows you how to preserve state from server to client and share the state within different page, you can expect the same state for "counter" when switching between Index and About page, observe that "counter" behaves differently from the "clock" example.
......@@ -16,4 +16,13 @@ export default class CounterContainer extends Container {
reset = () => {
this.setState({ count: 0 })
}
// this two methods are not setState as they work only before rendering
initState = count => {
this.state = { count }
}
resetState = () => {
this.initState(0)
}
}
export const counterStore = new CounterContainer()
import App, { Container } from 'next/app'
import React from 'react'
import { Provider } from 'unstated'
import { CounterContainer } from '../containers'
const counter = new CounterContainer()
import { counterStore } from '../containers/CounterContainer'
class MyApp extends App {
static async getInitialProps () {
// do your server state here
if (!process.browser) {
// reset state for each request
counterStore.resetState()
// process state, in this case counter start with 999
counterStore.initState(999)
return { serverState: counterStore.state }
} else {
return {}
}
}
constructor (props) {
super(props)
// pass the state to client store
// serverState will be reset when client navigate with Link
if (process.browser) {
counterStore.initState(props.serverState.count)
}
}
render () {
const { Component, pageProps } = this.props
return (
<Container>
<Provider inject={[counter]}>
<Provider inject={[counterStore]}>
<Component {...pageProps} />
</Provider>
</Container>
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册