NextJS + React 上下文:如何加载数据?
Posted
技术标签:
【中文标题】NextJS + React 上下文:如何加载数据?【英文标题】:NextJS + React context: How to load data? 【发布时间】:2019-06-09 02:10:24 【问题描述】:我已经为我的项目研究了 nextjs (7) + react 上下文。我的问题是如何通过Provider获取getInitialProps
中的数据?
【问题讨论】:
能否请您展示一些您尝试过的代码和无效的代码? 【参考方案1】:创建一个名为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
【讨论】:
这并没有回答这个问题,具体是关于如何在提供程序中获取数据。此答案中给出的示例根本不进行任何数据提取。以上是关于NextJS + React 上下文:如何加载数据?的主要内容,如果未能解决你的问题,请参考以下文章