1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

improve Unstated example so that it can shares state when switching pages (#5822)

* add new example

* update gitignore

* fix lint

* fix linting

* fix linting again

* update unstated example

* remove unsued var

* update readme
This commit is contained in:
tylim 2018-12-05 18:32:45 +08:00 committed by Tim Neutkens
parent 84223d39e7
commit 81cfea7d90
5 changed files with 57 additions and 4 deletions

2
examples/with-unstated/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
.vscode/
node_modules/

View file

@ -41,4 +41,7 @@ now
## The idea behind the example
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 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.

View file

@ -1,13 +1,16 @@
import App, {Container} from 'next/app'
import React from 'react'
import { Provider } from 'unstated'
import { CounterContainer } from '../containers'
const counter = new CounterContainer()
class MyApp extends App {
render () {
const {Component, pageProps} = this.props
return (
<Container>
<Provider>
<Provider inject={[counter]}>
<Component {...pageProps} />
</Provider>
</Container>

View file

@ -0,0 +1,37 @@
import React from 'react'
import Link from 'next/link'
import { Subscribe } from 'unstated'
import { ClockContainer, CounterContainer } from '../containers'
import { Clock, Counter } from '../components'
class About extends React.Component {
componentWillUnmount () {
clearInterval(this.timer)
}
render () {
return (
<Subscribe to={[ClockContainer, CounterContainer]}>
{
(clock, counter) => {
this.timer = clock.interval
return (
<div>
<Link href='/index'>
<button>
go to Index
</button>
</Link>
<div>
<Clock clock={clock} />
<Counter counter={counter} />
</div>
</div>
)
}
}
</Subscribe>
)
}
}
export default About

View file

@ -1,4 +1,5 @@
import React from 'react'
import Link from 'next/link'
import { Subscribe } from 'unstated'
import { ClockContainer, CounterContainer } from '../containers'
import { Clock, Counter } from '../components'
@ -15,8 +16,15 @@ class Index extends React.Component {
this.timer = clock.interval
return (
<div>
<Clock clock={clock} />
<Counter counter={counter} />
<Link href='/about'>
<button>
go to About
</button>
</Link>
<div>
<Clock clock={clock} />
<Counter counter={counter} />
</div>
</div>
)
}