【发布时间】:2017-09-16 01:41:32
【问题描述】:
我正在为我当前的 web 应用程序使用 redux 和 typescript。
定义通过@connect 接收redux-actions 的组件的props 以及来自父级的props 的最佳实践是什么?
示例:
// mychild.tsx
export namespace MyChildComponent {
export interface IProps {
propertyFromParent: string;
propertyFromRedux: string; // !!!! -> This is the problem
actionsPropertyFromRedux: typeof MyReduxActions; // !!!! -> And this
}
}
@connect(mapStateToProps, mapDispatchToProps)
export class MyChildComponent extends React.Component <MyChildComponent.IProps, any> {
... react stuff
}
function mapStateToProps(state: RootState) {
return {
propertyFromRedux: state.propertyFromRedux
};
}
function mapDispatchToProps(dispatch) {
return {
actionsPropertyFromRedux: bindActionCreators(MyReduxActions as any, dispatch)
};
}
// myparent.tsx
export class MyParentComponent extends React.Component <MyParentComponent.IProps, any> {
... react stuff
render(){
// typescript complains, because I am not passing `propertyFromRedux`!
return <div><MyChildComponent propertyFromParent="yay" /></div>;
}
}
在我看来,我有 2 个解决方案。
只需通过我的整个应用程序传递操作和状态。但这意味着我的整个应用程序会被重新渲染,即使只需要更改一些小的子组件。还是在我的顶级组件中监听所有商店更改的 redux 方式?然后我必须在
shouldComponentUpdate中为非平面对象的道具编写大量逻辑。将
IProps中的参数设置为MyChildComponent可选,如下所示:
-
// mychild.tsx
export namespace MyChildComponent {
export interface IProps {
propertyFromParent: string;
propertyFromRedux?: typeof MyAction; // This is the problem
}
}
还有其他方法吗?以上两种方式在我看来都太乱了。
【问题讨论】:
标签: javascript reactjs typescript redux react-redux