我有一个带有计数器减速器和存储的计数器组件,在打字稿中实现。我无法通过打字将组件连接到商店。当我在商店中定义一个状态时,我遇到了一个问题。
我也在使用connected-react-router,它包装了组合reducer,但我仍然收到以下错误:
错误:
No overload matches this call.
The last overload gave the following error.
Argument of type '(state: AppState) => { counter: number; router: RouterState<PoorMansUnknown>; }' is not assignable to parameter of type 'MapStateToPropsParam<StateProps, RouteComponentProps<any, StaticContext, PoorMansUnknown>, DefaultRootState>'.
Type '(state: AppState) => { counter: number; router: RouterState<PoorMansUnknown>; }' is not assignable to type 'MapStateToPropsFactory<StateProps, RouteComponentProps<any, StaticContext, PoorMansUnknown>, DefaultRootState>'.
Types of parameters 'state' and 'initialState' are incompatible.
Type 'DefaultRootState' is missing the following properties from type 'AppState': router, counter
错误在这一行:
export default connect<StateProps, DispatchProps, RouteComponentProps<any>>(
mapStateToProps,
mapDispatchToProps
)(Home);
零件:
const Home = (props: StateProps & DispatchProps) => {
function handleClick() {
props.increment();
}
const { decrementAction } = props;
return (
<div>
Home {JSON.stringify(props.counter.number)}
<button type="button" onClick={handleClick}>
Increment
</button>
<button type="button" onClick={decrementAction}>
Decrement
</button>
</div>
);
};
interface StateProps {
counter: number;
}
interface DispatchProps {
increment: () => void;
decrementAction: () => void;
}
function mapStateToProps(state: AppState) {
return {
counter: state.counter,
router: state.router
};
}
export default connect<StateProps, DispatchProps, RouteComponentProps<any>>(
mapStateToProps,
mapDispatchToProps
)(Home);
店铺:
export interface AppState {
router: RouterState;
counter: number;
}
export const rootReducer = (history: History) =>
combineReducers({
counter: counterReducer,
router: connectRouter(history)
});
// export type AppState = ReturnType<typeof rootReducer>;
export default function configureStore(history: History) {
const middlewares = [routerMiddleware(history), thunkMiddleware];
if (process.env.NODE_ENV === `development`) {
/* eslint-disable global-require */
/* @typescript-eslint/no-var-requires */
const { logger } = require(`redux-logger`);
middlewares.push(logger);
}
const middleWareEnhancer = applyMiddleware(...middlewares);
const store = createStore(
rootReducer(history),
composeWithDevTools(middleWareEnhancer)
);
return store;
}
减速器:
import {
CounterState,
CounterActionTypes,
INCREMENT,
DECREMENT
} from './types';
const initialState: CounterState = {
number: 0
};
export const counterReducer = (
state = initialState,
action: CounterActionTypes
): CounterState => {
switch (action.type) {
case INCREMENT:
return { number: state.number + 1 };
case DECREMENT:
return { number: state.number - 1 };
default:
return state;
}
};