我正在尝试将 React+Redux 组件的示例复制到 typescript :https://medium.com/@stowball/a-dummys-guide-to-redux-and-thunk-in-react-d8904a7005d3
我遇到了函数的死胡同:
export default connect(mapStateToProps, mapDispatchToProps)(ItemList);
我收到一个关于它如何不能映射到 ItemList 的错误。
我认为解决这个问题的一种方法是将类声明更改为:
class ItemList extends React.Component<{proper component map}, {proper state map}> {
但是,如果我这样做是因为现在已经映射了 props,我不能简单地将 ItemList 包含在内,并且现在需要提供参数。
另一种选择可能是:(props as any).fetchData() 但这感觉不对。
有解决办法吗?我在 typescript 中做错了 React+Redux 吗?
最佳答案
创建完所有内容后,您可以使用connect
将其导出。
interface PassedProps {
productId: number;
}
interface StateToProps {
addedProductIds: number[];
quantityById: { [key: string]: number };
quantity: number;
}
interface DispatchToProps {
addToCart: (productId: number) => void;
removeFromCart: (productId: number) => void;
}
// Needs to be added to src/store:GlobalStore interface with the correct prop name created from the name of the reducer
export interface CartState {
addedProductIds: number[];
quantityById: { [key: string]: number };
}
const mapStateToProps = (globalState: GlobalState): StateToProps => {
const state: CartState = globalState.cart;
return {
addedProductIds: state.addedProductIds,
quantityById: state.quantityById,
quantity: Object.keys(state.quantityById).reduce( (sum: number, key: string) => state.quantityById[key] + sum, 0)
};
};
const mapDispatchToProps = (dispatch: Dispatch<any>): DispatchToProps => {
return {
addToCart: (productId: number) => dispatch({ type: 'ADD_TO_CART', productId } as AddToCartAction),
removeFromCart: (productId: number) => dispatch({ type: 'REMOVE_FROM_CART', productId } as RemoveFromCartAction),
};
}
export type Props = PassedProps & StateToProps & DispatchToProps;
class CartButton extends Component<Props, CartState> {
render() {
const { quantity } = this.props;
return (
<View>
<Text>
{ this.props.addedProductIds.length } type item is in the cart, totals to { quantity } item.
</Text>
<View>
<Button
onPress={this.onPressAdd.bind(this)}
title="Add to Cart"
color="#841584"
/>
<Button
onPress={this.onPressRemove.bind(this)}
title="Removefrom Cart"
color="#841584"
/>
</View>
</View>
);
}
onPressAdd() {
this.props.addToCart(this.props.productId);
}
onPressRemove() {
this.props.removeFromCart(this.props.productId);
}
}
export default connect<StateToProps, DispatchToProps, PassedProps>(mapStateToProps, mapDispatchToProps)(CartButton);
然后您可以使用它来指定要传递的所需 Prop (PassedProps 接口(interface)):
import CartButton from '../components/CartButton';
// ....
render() {
return(<CartButton productId={5} />)
}
关于javascript - 将 React 组件转换为 Typescript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46195451/