[英]Next.Js Redux Wrapper w/ Typescript - Implementation error, store does not exist as type
I am implementing state management for React.我正在为 React 实现状态管理。 I am using Next.js and Typescript.我正在使用 Next.js 和 Typescript。
I used the next redux wrapper and have the following on /pages/_app.js as instructed by the guide.我使用了下一个 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);
I get a typescript error on the store variable I'm trying to declare in the render() function, which throws me an error as follows:我试图在 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)
I am unsure as to what the issue is.我不确定问题是什么。 I am not able to access any type/interface to allow store to be a variable.我无法访问任何类型/接口以允许 store 成为变量。 And this is interesting because this is the solution for many developers when using Typescript/Redux/Next.js.这很有趣,因为这是许多开发人员在使用 Typescript/Redux/Next.js 时的解决方案。
Any help/pointers would be appreciated, thank you.任何帮助/指针将不胜感激,谢谢。
Container
is deprecated now; Container
现已弃用; use App
instead and pass it props with Store
.改用App
并通过Store
传递道具。 Setting something to 'any' because it's giving you errors is not a good solution and kind of defeats the whole purpose of using TypeScript in the first place.将某些东西设置为“任何”,因为它会给您带来错误,这不是一个好的解决方案,并且首先违背了使用 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)
Fixed the issue.修复了问题。
I added a simple我添加了一个简单的
interface Props {
store: any
}
To circumvent the Typescript error.规避打字稿错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.