next.js is one of the popular SSR and reactjs base frameworks, but some difference between koa-cola and next.js.
fetch data
next.js provide static method "getInitialProps" to fetch dataļ¼
1
2
3
4
5
6
7
8
9
10
11
12
13
import React from'react'
exportdefaultclassextendsReact.Component{
staticasync getInitialProps ({ req }) {
return req
? { userAgent: req.headers['user-agent'] }
: { userAgent: navigator.userAgent }
}
render () {
return <div>
Hello World {this.props.userAgent}
</div>
}
}
koa-cola use Cola decorator to fetch data:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from'react'
var { Cola } = require('koa-cola/client');
@Cola({
initData : {
userAgent : req
? { userAgent: req.headers['user-agent'] }
: { userAgent: navigator.userAgent }
}
})
exportdefaultclassextendsReact.Component{
render () {
return <div>
Hello World {this.props.userAgent}
</div>
}
}
the first way fetch data in koa-cola props actually come from react-redux, because koa-cola combines all pages reducer into redux, so in browser espcially in SPA, you can share this kind of props in all pages. while next.js has not support this yet.
support children components data fetch
next.js does not support fetch data in children components:
Note: getInitialProps can not be used in children components. Only in pages.
but in koa-cola this can easy be supported by using the decorator "include":
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// in child component
@Cola({
initData : {
userAgent : req
? { userAgent: req.headers['user-agent'] }
: { userAgent: navigator.userAgent }
}
})
classChildextendsReact.Component{
render () {
return <div>
Hello World {this.props.userAgent}
</div>
}
}
// in page
var { Cola, include } = require('koa-cola/client');