我認為使用 react-redux 進行打字有一些我沒有得到的東西。考慮一下:
import React from 'react';
import { Text } from 'react-native';
import { connect } from 'react-redux';
import { AnyAction } from 'redux';
import { ThunkDispatch } from 'redux-thunk';
function SomeComponent_Unconnected(
props: React.PropsWithChildren<{ foo: string; handleSmth: () => void }>
) {
return <>
<Text>{props.foo}</Text>
{props.children}
</>;
}
interface IState {
foo: string;
}
const SomeComponent = connect(
// map state to props
(state: IState) => ({ foo: state.foo }),
// map dispatch to props
(dispatch: ThunkDispatch<IState, any, AnyAction>, getState: () => IState) => ({
handleSmth: () => {
console.log('something happened');
},
}),
)(SomeComponent_Unconnected);
export function AnotherComponent() {
return (
<SomeComponent> {/* TS error here, see below */}
<Text>Test</Text>
</SomeComponent>
);
}
這里是 React 中 Redux 的基本用法,但我遇到了一個奇怪的 TS 錯誤AnotherComponent:
輸入'{孩子:(字串|元素)[]; }' 不可分配給型別 '() => IState'。
輸入'{孩子:(字串|元素)[]; }' 不匹配簽名 '(): IState'.ts(2322)
請注意,如果我洗掉該功能的mapDispatchToProps一部分,此錯誤就會消失connect。
你知道這個錯誤來自哪里嗎?謝謝 !
uj5u.com熱心網友回復:
來自 redux 檔案:If your mapDispatchToProps function is declared as taking two parameters, it will be called with dispatch as the first parameter and the props passed to the connected component as the second parameter.
它沒有getState您提供的引數。ThunkDispatch您過早地關閉了泛型型別引數>。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/454265.html
