typescript - React + typescript + Redux 连接功能不起作用
问题描述
我对在 React 中使用 Typescript 有点陌生。我试图将我的 Redux 与我的容器组件连接起来,但由于某种原因,它一直给我类型错误。我经历了许多堆栈溢出帖子,但仍然无法理解发生了什么。
我的 redux tpes 文件:
export interface StoreState {
languageName: string,
enthusiasmLevel: number
}
我的容器组件文件:
// React imports
import React from 'react';
import {Link } from 'react-router-dom';
import * as actions from '../../redux/actions/actions';
import { StoreState } from '../../redux/types/types';
import { connect } from 'react-redux';
import { Dispatch } from 'redux';
interface NavbarComponentProps {
name: string;
enthusiasmLevel?: number;
onIcrement?: () => void;
onDecrement?: () => void;
}
interface DispatchFromProps {
onDecrement: () => void,
onIncrement: () => void
}
interface StateFromProps {
name: string,
enthusiasmLevel: number
}
type Props = StateFromProps & DispatchFromProps & NavbarComponentProps;
class NavbarContainer extends React.Component<Props, {}> {
public static defaultProps = {
enthusiamsLevel: 1
}
public render() {
return (
<div className='App'>
navbar works.
<Link to='/'>left nav</Link>
{/*
<p>Hello {name + getExclamationMarks(this.props.enthusiasmLevel)} </p> */}
<button onClick={this.props.onDecrement}> - </button>
<button onClick={this.props.onIcrement}> + </button>
</div>
);
}
}
function mapStateToProps({ enthusiasmLevel, languageName}: StoreState) {
return {
enthusiasmLevel,
name: languageName
}
}
function mapDispatchToProps(dispatch: Dispatch<actions.EnthusiamsAction>) {
return {
onDecrement: () => dispatch(actions.decrementEnthusiasm()),
onIncrement: () => dispatch(actions.incrementEnthusiasm())
}
}
export default connect<StateFromProps, DispatchFromProps, NavbarComponentProps, StoreState>(mapStateToProps, mapDispatchToProps)(NavbarContainer);
我猜想将语言名称重置为名称存在问题,但是即使更改也无济于事。
任何帮助将非常感激。干杯!
解决方案
相关签名如下
<TStateProps = {}, TDispatchProps = {}, TOwnProps = {}, State = {}>(
mapStateToProps: MapStateToPropsParam<TStateProps, TOwnProps, State>,
mapDispatchToProps: MapDispatchToPropsNonObject<TDispatchProps, TOwnProps>
)
省略最后一个State
时,默认为{}
.
你应该打电话connect<StateFromProps, DispatchFromProps, NavbarContainerProps, StoreState>(...)(...)
。想想connect<ReduxInjected, DispatchInjected, GivenByParentWhenUsingThisComponent, ReduxStoreType>
。
请注意,我稍微更改了界面,您Props
应该NavbarContainerProps
并且仅包含手动传入的道具(而不是从商店传入)。
然后我喜欢编写一个类型别名type Props = StateFromProps & DispatchFromProps & NavbarContainerProps;
,用于定义组件。
class NavbarContainer extends React.Component<Props, {}> {
...
}
推荐阅读
- sql - 为什么 PostgreSQL 对布尔 WHERE 条件进行排序?
- scala - How to create data to complex struct type , struct array type in Scala Python and HiveQL?
- vb.net - KeyDown 与组合框
- powershell - 如何使用powershell脚本删除小于x kb的文件
- deeplab - deeplab 预测黑色蒙版
- rancher - 集群外的牧场主反向代理
- java - 在通话期间使用设备麦克风
- python - 如何更改我的 python 乌龟窗口的大小?
- java - Java - 日期时区转换
- c# - 在 Office 365 iframe 上使用 C# 本地显示访问 word 文档