【问题标题】:Can i wrap the React Context API inside getInitialProps/getServerSideProps/getStaticProps我可以将 React Context API 包装在 getInitialProps/getServerSideProps/getStaticProps 中吗
【发布时间】:2020-10-22 08:22:55
【问题描述】:

如何在 NextJs 的 getInitialProps/getServerSideProps/getStaticProps 中使用 React Context API 调用动作创建者?

使用带有 NextJs 的 redux,我可以访问 store,然后分派一个动作创建者。但是,使用 React Context API 我不知道该怎么做。

Redux 示例:

Search.getInitialProps = async ({ store }) => {
   store.dispatch(fetch('next-js'));
});

如何使用 React Context API 做到这一点?

谢谢!!!

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    在上下文提供者中,你可以做这样的事情

    export async function getStaticProps() {
            // Call an external API endpoint to get posts.
            // You can use any data fetching library
            const res = await fetch("https://www.mocky.io/")
            const search = await res.json()
    
            // By returning { props: search }, the Search component
            // will receive `search` as a prop at build time
            return {
                props: {
                    search,
                },
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2019-05-27
      • 2020-02-08
      • 1970-01-01
      • 2021-05-31
      • 1970-01-01
      • 2018-09-02
      相关资源
      最近更新 更多