我已经为我的项目研究了nextjs(7)+ react上下文。我的问题是提供商如何在getInitialProps
中获取数据?
答案 0 :(得分:0)
创建一个名为components/CounterProvider.js
import React, { Component } from 'react'
/* First we will make a new context */
const CounterContext = React.createContext()
/* Then create a provider Component */
class CounterProvider extends Component {
state = {
count: 0
}
increase = () => {
this.setState({
count: this.state.count + 1
})
}
decrease = () => {
this.setState({
count: this.state.count - 1
})
}
render () {
return (
<CounterContext.Provider
value={{
count: this.state.count,
increase: this.increase,
decrease: this.decrease
}}
>
{this.props.children}
</CounterContext.Provider>
)
}
}
/* then make a consumer which will surface it */
const CounterConsumer = CounterContext.Consumer
export default CounterProvider
export { CounterConsumer }
然后在pages/_app.js
中使用此代码使用提供程序并在所有组件之间共享它:
import App, { Container } from 'next/app'
/* First we import our provider */
import CounterProvider from '../components/CounterProvider'
class MyApp extends App {
render () {
const { Component, pageProps } = this.props
return (
<Container>
{/* Then we wrap our components with the provider */}
<CounterProvider>
<Component {...pageProps} />
</CounterProvider>
</Container>
)
}
}
export default MyApp
最终将其用于任何这样的组件:pages/index.js
import React, { Component } from 'react'
/* First we import the consumer */
import { CounterConsumer } from '../components/CounterProvider'
export default class index extends Component {
render () {
return (
/* Then we use our context through render props */
<CounterConsumer>
{({ count, increase, decrease }) => (
<div>
<p>Counter: {count}</p>
<button onClick={increase}>Increase</button>
<button onClick={decrease}>Decrease</button>
</div>
)}
</CounterConsumer>
)
}
}
有关更多信息,请关注this example