我对 React 和 Redux 很陌生,我正在关注 this tutorial ,
在关于制作容器
的部分,我收到错误(无法编译):
./src/containers/Hello.tsx
(24,61): error TS2345: Argument of type 'typeof Hello' is not assignable to parameter of type 'ComponentType<{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusia...'.
Type 'typeof Hello' is not assignable to type 'StatelessComponent<{ enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnt...'.
Type 'typeof Hello' provides no match for the signature '(props: { enthusiasmLevel: number; name: string; } & { onIncrement: () => IncrementEnthusiasm; onDecrement: () => DecrementEnthusiasm; } & { children?: ReactNode; }, context?: any): ReactElement<any> | null'.
由于我现阶段正在逐步遵循教程,因此我不确定如何修复此错误。
你好容器:
import Hello from '../components/Hello';
import * as actions from '../actions/';
import { StoreState } from '../types/index';
import { connect, Dispatch } from 'react-redux';
export function mapStateToProps({ enthusiasmLevel, languageName }: StoreState) {
return {
enthusiasmLevel,
name: languageName,
};
}
export function mapDispatchToProps(dispatch: Dispatch<actions.EnthusiasmAction>) {
return {
onIncrement: () => dispatch(actions.incrementEnthusiasm()),
onDecrement: () => dispatch(actions.decrementEnthusiasm()),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Hello);
Hello 组件:
import * as React from 'react';
import './Hello.css';
export interface Props {
name: string; // required
enthusiasmLevel?: number; // optional (using ? after its name)
onIncrement?: () => void;
onDecrement?: () => void;
}
class Hello extends React.Component<Props, object> {
render () {
const { name, enthusiasmLevel = 1, onIncrement, onDecrement } = this.props;
if (enthusiasmLevel <= 0) {
throw new Error('You could be a little more enthusiastic.');
}
return(
<div className="hello">
<div className="greeting">
Hello {name + getExclamationMarks(enthusiasmLevel)}
</div>
<div>
<button onClick={onDecrement}>-</button>
<button onClick={onIncrement}>+</button>
</div>
</div>
);
}
}
export default Hello;
function getExclamationMarks (n: number) {
return Array(n + 1).join('!');
}
最佳答案
该错误表明 connect 函数需要一个无状态组件,而您提供一个有状态组件 - 因为 React.Component 的第二个参数是 object>.
我建议搭配:
const Hello = ({
name,
enthusiasmLevel = 1,
onIncrement,
onDecrement
}: Props) => {
if (enthusiasmLevel <= 0) {
throw new Error('You could be a little more enthusiastic.');
}
return(
<div className="hello">
<div className="greeting">
Hello {name + getExclamationMarks(enthusiasmLevel)}
</div>
<div>
<button onClick={onDecrement}>-</button>
<button onClick={onIncrement}>+</button>
</div>
</div>
);
}
关于javascript - 构建期间发生 react 、redux 和 typescript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48117582/