简体   繁体   中英

React Redux Typescript error with AnyAction when implementing Redux-Persist

I am trying to implement redux-persist into my React project. Redux was working fine, but when I was implementing redux-persist, I started to get this error:

   Types of property 'dispatch' are incompatible.
     Type 'Dispatch<{ type: string; payload: any; }>' is not assignable to type 'Dispatch<AnyAction>'.
       Type 'AnyAction' is not assignable to type '{ type: string; payload: any; }'.  TS2345
     19 | const store = createStore(persistedReducer)
     20 |
   > 21 | let persistor = persistStore(store)
        |                              ^
     22 |
     23 | ReactDOM.render(
     24 |   <Provider store={store}>

I am assuming it has to do with my reducer and the way I am defining the properties in the Action, but I haven't been able to figure it out.

index.tsx

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
import {Provider} from 'react-redux';
import {createStore} from 'redux'
import reducer from './redux/reducer';
import { persistStore, persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage'; // defaults to localStorage for web
import { PersistGate } from 'redux-persist/integration/react';

const persistConfig = {
  key: 'root',
  storage
}

const persistedReducer = persistReducer(persistConfig, reducer)

const store = createStore(persistedReducer)

let persistor = persistStore(store)

ReactDOM.render(
  <Provider store={store}>
    <PersistGate loading={null} persistor={persistor}>
      <App />
    </PersistGate>
  </Provider>,
  document.getElementById('root'));

serviceWorker.unregister();

reducer.ts

const defaultState = {
  user: {}
}

export default function reducer(
  state = defaultState,
  {type, payload} : {type: string; payload: any}
): any {
  switch(type){
    case 'SET_USER_STATE':
      return {
        ...state,
        user: {
          username:payload
        }
      }
  }
  return state
}

actions.tx

export const setUserState = (payload: any) => {
  return { type: 'SET_USER_STATE', payload}
}

Fixed the problem.

The line

{type, payload} : {type: string; payload: any}

needed to be changed to

{type, payload} : AnyAction

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM