【问题标题】:Next.Js Redux Wrapper w/ Typescript - Implementation error, store does not exist as typeNext.Js Redux Wrapper w/ Typescript - 实现错误,存储不作为类型存在
【发布时间】:2020-01-01 11:02:54
【问题描述】:

我正在为 React 实现状态管理。我正在使用 Next.js 和 Typescript。

我使用了下一个 redux 包装器,并按照指南的指示在 /pages/_app.js 上有以下内容。

import React from "react";
import {createStore} from "redux";
import {Provider} from "react-redux";
import App, {Container} from "next/app";
import withRedux from "next-redux-wrapper";
import configureStore from '../state/store';

class MyApp extends App {

    static async getInitialProps ({Component, ctx}) {
        return {
          pageProps: (Component.getInitialProps ? await Component.getInitialProps(ctx) : {})
        }
      }

    render() {
        const {Component, pageProps, store} = this.props;
        return (
            <Container>
                <Provider store={store}>
                    <Component {...pageProps} />
                </Provider>
            </Container>
        );
    }

}

export default withRedux(configureStore)(MyApp);

我尝试在 render() 函数中声明的 store 变量出现打字稿错误,这会引发如下错误:

const store: any
Property 'store' does not exist on type 'Readonly<AppInitialProps & { Component: NextComponentType<NextPageContext, any, {}>; router: Router; }> & Readonly<{ children?: ReactNode; }>'.ts(2339)

我不确定问题是什么。我无法访问任何类型/接口以允许 store 成为变量。这很有趣,因为这是许多开发人员在使用 Typescript/Redux/Next.js 时的解决方案。

任何帮助/指针将不胜感激,谢谢。

【问题讨论】:

    标签: reactjs typescript react-redux next.js


    【解决方案1】:

    Container 现已弃用;改用App 并使用Store 传递它的道具。将某些内容设置为“任何”,因为它会给您带来错误,这不是一个好的解决方案,并且首先违背了使用 TypeScript 的全部目的。

    import App, { AppContext } from 'next/app'
    import { Provider } from 'react-redux'
    import withRedux from 'next-redux-wrapper'
    import { Store } from 'redux'
    import Page from '../components/Page'
    import { initializeStore } from '../store'
    
    interface Props {
      store: Store;
    }
    
    class MyApp extends App<Props> {
      static async getInitialProps({ Component, ctx }: AppContext) {
        return {
          pageProps: (Component.getInitialProps 
            ? await Component.getInitialProps(ctx) 
            : {}),
        }
      }
    
      render() {
        const { Component, pageProps, store } = this.props
    
        return (
          <Provider store={store}>
            <Page>
              <Component {...pageProps} />
            </Page>
          </Provider>
        )
      }
    }
    
    export default withRedux(initializeStore)(MyApp)
    

    【讨论】:

    • 但是我应该怎么做才能在某些页面中存储? NextPageContext 没有字段 store 并且我不明白应该为我的页面组件(功能组件)设置什么类型
    【解决方案2】:

    解决了这个问题。

    我添加了一个简单的

    interface Props {
        store: any
    }
    

    为了规避 Typescript 错误。

    【讨论】:

    • 这不是修复。如果你打算这样做,你也可以删除 Typescript。
    猜你喜欢
    • 1970-01-01
    • 2023-02-06
    • 2021-12-31
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多