【发布时间】:2019-02-27 20:03:52
【问题描述】:
上下文:简单的 React Native 应用利用 Redux 来管理复杂性。
版本:
- 打字稿 v3.0.3
- react-native v0.56.0
- redux v4.0.0
- @types/react-redux v6.0.9
- @types/redux v3.6.0
问题:我的 JSX 主组件看不到属性(cmets 中包含的错误)。
第一个文件:
//app.tsx
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<MainRedux ownProp="as"/> //[1]: Type '{ ownProp: string; }' is not assignable to type 'Readonly<AllProps>'. Property 'appPermissions' is missing in type '{ ownProp: string; }'.
</Provider>
);
}
}
和第二个文件:
//MainRedux.tsx
export interface ApplicationState { //originally in another file
appPermissions: AppPermissionsState;
//...
}
type StateProps = ApplicationState; //alias appPermissions is in the Application State
interface DispatchProps {
getPermissions: typeof getPermissions;
//...
}
interface OwnProps {
ownProp: string;
}
type AllProps = StateProps & DispatchProps & OwnProps;
export class MainRedux extends React.Component<AllProps> {
constructor(props: AllProps) {
super(props);
props.getPermissions(); //[2]: TypeError: undefined is not a function (evaluating 'props.getPermissions()')
}
//...
} //class
//...
const mapStateToProps: MapStateToProps<
StateProps,
OwnProps,
ApplicationState
> = (state: ApplicationState, ownProps: OwnProps): StateProps => {
return state;
};
const mapDispatchToProps: MapDispatchToPropsFunction<
DispatchProps,
OwnProps
> = (dispatch: Dispatch<AnyAction>, ownProps: OwnProps): DispatchProps => ({
getPermissions: bindActionCreators(getPermissions, dispatch)
//...
});
export default connect<StateProps, DispatchProps, OwnProps, ApplicationState>(
mapStateToProps,
mapDispatchToProps
)(MainRedux);
而,[1] 是编译时错误,[2] 是运行时错误。
谁能告诉我怎么了?提前谢谢你。
编辑:我将一些调试信息放入mapStateToProps 和mapDispatchToProps,但似乎connect 没有调用它们。我可以更进一步,假设甚至 connect 都没有被调用。
【问题讨论】:
-
在你的 MainRedux 类中添加一个方法:
componentDidMount () {console.log(this.props)}你能看到那里的任何道具吗?第一个错误是 TypeScript 错误。 -
@JRK,[1] 是的,这就是 TS 错误。我听从了你的建议。
this.props为空 ({})。 -
@JRK,过了一会儿我在
this.props里面有了{"ownProp":"as"}。不要问我这是怎么发生的,因为我不知道:/ 其余必要的属性仍然缺失。 -
github上有完整的代码吗?不经过测试很难弄清楚。
-
@JRK,还没有。把它放在那里还为时过早。
标签: typescript react-native react-redux