3

我想要 JavaScript -> TypeScript!但是,太难了。

// store.js

import { applyMiddleware, createStore, compose, Store } from "redux";
import createSagaMiddleware, { Task } from "redux-saga";
import { createWrapper } from "next-redux-wrapper";
import { composeWithDevTools } from "redux-devtools-extension";

import reducer from "./reducers";
import rootSaga from "./sagas";

const configureStore = () => {
  const sagaMiddleware = createSagaMiddleware();
  const middlewares = [sagaMiddleware];
  const enhancer =
    process.env.NODE_ENV === "production"
      ? compose(applyMiddleware(...middlewares))
      : composeWithDevTools(applyMiddleware(...middlewares));
  const store = createStore(reducer, enhancer);
  store.sagaTask = sagaMiddleware.run(rootSaga);
  return store;
};

const wrapper = createWrapper(configureStore, {
  debug: process.env.NODE_ENV === "development",
});

export default wrapper;
// reducers/index.ts

import { HYDRATE } from "next-redux-wrapper";
import { AnyAction, combineReducers } from "redux";

import url, { IUrlReducerState } from "./reducer_url";
import user, { IUserReducerState } from "./reducer_user";

export type State = {
  url: IUrlReducerState;
  user: IUserReducerState;
};

const rootReducer = (state: State, action: AnyAction) => {
  switch (action.type) {
    case HYDRATE:
      return action.payload;

    default: {
      const combineReducer = combineReducers({
        url,
        user,
      });
      return combineReducer(state, action);
    }
  }
};
export type RootState = ReturnType<typeof rootReducer>;
export default rootReducer;

reducers/index.ts<-这是你的做法吗?我已经改变了一点。

// pages/index.js

import { END } from "redux-saga";
import wrapper from "../store";

export const getServerSideProps = wrapper.getServerSideProps(
  async (context) => {

    context.store.dispatch({
      type: LOAD_USER_REQUEST,
    });

    context.store.dispatch(END);
    await context.store.sagaTask.toPromise();
  }
);

看了官方文档,看不懂:https ://github.com/kirill-konshin/next-redux-wrapper#getserversideprops

这些代码在 JavaScript 中没有问题。但是 TypeScript 有一个问题。

4

2 回答 2

5

以下是我看到的问题:

  1. 你会得到一个错误,createStore(reducer, enhancer)因为你reducer不适合 type (state: State | undefined, action: AnyAction) => State。您必须使您的减速机适合这种类型。state现在的问题是你的减速器不允许 for undefined

改变

const rootReducer = (state: State, action: AnyAction) => {

const rootReducer = (state: State | undefined, action: AnyAction): State => {
  1. store.sagaTask = sagaMiddleware.run(rootSaga);因为 redux 创建的对象store没有名为sagaTask. 这里有另一个讨论。

这是一个基于 next-redux-wrapper 文档的解决方案:

为您的商店定义一个新界面,其中包括任务

export interface SagaStore extends Store<State, AnyAction> {
  sagaTask: Task;
}

代替

store.sagaTask = sagaMiddleware.run(rootSaga);

(store as SagaStore).sagaTask = sagaMiddleware.run(rootSaga);

代替

await context.store.sagaTask.toPromise();

await (context.store as SagaStore).sagaTask.toPromise();
于 2020-10-02T01:16:45.890 回答
1

我在尝试以适当的方式将 Redux 与 Next 同步时也遇到了一些糟糕的情况,他们使用 next-redux-wrapper 创建了一个项目模板,该模板目前正在工作并遵循 next-redux-wrapper 的指导方针. 你可以看一下:

https://github.com/felipemeriga/next-typescript-redux-template

基本上我是这样创建包装器的:

const thunkMiddleware = thunk.withExtraArgument({}) as ThunkMiddleware<IStoreState, AnyAction>;

// create a makeStore function
// This makeStore is needed for the wrapper, for every new page that is called, a new store with the current values will be created
const makeStore: MakeStore<IStoreState> = (context: Context) => createStore(reducers, composeWithDevTools(applyMiddleware(thunkMiddleware)));

export type ExtraArgument = {};

export type ThunkCreator<R = Promise<any>> = ActionCreator<ThunkAction<R, IStoreState, ExtraArgument, AnyAction>>;

// export an assembled wrapper
// this wrapper will be used to every page's component, for injecting the store and actions into it.
const wrapper = createWrapper<IStoreState>(makeStore, {debug: false});

export default wrapper;

然后覆盖了_app.tsx:

// For default you don't need to edit _app.tsx, but if you want to wrapper the pages with redux wrapper, you need
// to override _app.tsx with this code bellow
class MyApp extends App {
    // @ts-ignore
    static async getInitialProps({Component, ctx}) {
        return {
            pageProps: {
                // Call page-level getInitialProps
                ...(Component.getInitialProps ? await Component.getInitialProps(ctx) : {}),
            }
        };
    }

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

}

export default wrapper.withRedux(MyApp);

最后注入 index.tsx 组件:

interface IProps {
    tick: ITickState
    updateAnnouncement: any
}

interface IState {}

interface IDispatchProps {
    onUpdateTick: (message: string) => ITickState,
    thunkAsyncFunction: () => Promise<any>;
}

type Props = IProps & IState & IDispatchProps

class App extends React.Component<Props> {

    constructor(props: Props) {
        super(props);
    }

    async componentWillUnmount(): Promise<void> {
        await this.props.thunkAsyncFunction();
    }

    render() {
        return (
            <Layout title="Home | Next.js + TypeScript Example">
                <h1>Hello Next.js </h1>
                <p>
                    <Link href="/about">
                        <a>About</a>
                    </Link>
                </p>
                <div>
                    The current tick state: {this.props.tick.message}
                </div>
            </Layout>
        );
    }
}

const mapStateToProps = (state: IStoreState): {tick: ITickState} => ({
    tick: getTickState(state)
});

const mapDispatchToProps = (dispatch: any): IDispatchProps => {
    return {
        onUpdateTick: (message: string) =>
            dispatch(updateTick(message)),
        thunkAsyncFunction: () => dispatch(thunkAsyncFunction())
    }
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

// As the wrapper is injected in _app.tsx, for every component(page) that will interact with Redux and Thunk
// you need to place this piece of code bellow, that will get the static props from the wrapper, and inject on your
// component
export const getStaticProps = wrapper.getStaticProps(
    ({}) => {
    }
);

于 2021-02-03T12:29:34.653 回答