【发布时间】:2021-03-23 14:44:03
【问题描述】:
您好,我需要 react typescript 的连接模式
我有减速器
type State = {
version: number,
a?: string
}
interface ActionC {
type: string
payload?: number
}
type IAction = ActionA | ActionB | ActionC;
const reducer = (state: State = initialState, action: IAction) => {
// The reducer normally looks at the action type field to decide what happens
switch (action.type) {
// Do something here based on the different types of actions
default:
// If this reducer doesn't recognize the action type, or doesn't
// care about this specific action, return the existing state unchanged
return state
}
}
但是当我绑定时使用连接
export const App: FunctionComponent<{ version: number}> = (props) => {
return (
<div>APP {props.version}</div>
)
}
const mapStateToProps = (state: State) => {
return {
version: state.version
}
};
export default connect(mapStateToProps)(App);
我有错误
类型“{}”中缺少属性“版本”,但类型中是必需的 '省略'。 TS2741
如何解决这个问题?
【问题讨论】:
-
除非你有意将 UI 与状态完全分离(这样做有充分的理由),否则你可以省去一些痛苦并采用
useState钩子而不是使用connect。现在你可以去掉connectHOC 的所有样板,你的组件体看起来像这样const version = useState(state => state.version); return <div>{version}</div>。现在这容易多了。 -
@spender 我相信你的意思是
useSelector,而不是useState -
@NicholasTower 确实如此。谢谢指正。
标签: reactjs typescript redux