gpt4 book ai didi

javascript - 实现 Redux-Persist 时使用 AnyAction react Redux Typescript 错误

转载 作者:行者123 更新时间:2023-12-05 08:12:37 25 4
gpt4 key购买 nike

我正在尝试将 redux-persist 实现到我的 React 项目中。 Redux 工作正常,但是当我实现 redux-persist 时,我开始遇到这个错误:

   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}>

我假设它与我的 reducer 以及我在 Action 中定义属性的方式有关,但我一直无法弄清楚。

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}
}

最佳答案

解决了问题。

线

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

需要改成

{type, payload} : AnyAction

关于javascript - 实现 Redux-Persist 时使用 AnyAction react Redux Typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61050171/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com