我有根据react-redux-typescript-boilerplate创建的应用程序,我已经创建了该文件:
import * as React from 'react';
import { connect } from 'react-redux';
import { RootState } from 'app/reducers';
export namespace LasarTitle {
export interface Props {
title: string;
loading: boolean;
};
};
@connect(
(state: RootState): LasarTitle.Props => {
return { title: state.title, loading: state.loading };
},
() => { }
)
export class LasarTitle extends React.Component<LasarTitle.Props> {
static defaultProps: Partial<LasarTitle.Props> = {
title: ''
};
constructor(props: LasarTitle.Props, context?: any) {
super(props, context);
}
render() {
const title = this.props.loading ? 'loading...' : this.props.title;
return (
<div>
<input readOnly={true} value={title} />
</div>
);
}
}
与containers/App/index.tsx完全相同,它具有名称空间并以相同的名称连接到组件上。
我的代码有什么问题?我没有发现任何错别字或错误。我的代码和样板之间有什么区别?
答案 0 :(得分:2)
该错误非常明显。您只需要在类后移动名称空间声明即可。
import * as React from 'react';
import { connect } from 'react-redux';
import { RootState } from 'app/reducers';
@connect(
(state: RootState): LasarTitle.Props => {
return { title: state.title, loading: state.loading };
},
() => { }
)
export class LasarTitle extends React.Component<LasarTitle.Props> {
static defaultProps: Partial<LasarTitle.Props> = {
title: ''
};
constructor(props: LasarTitle.Props, context?: any) {
super(props, context);
}
render() {
const title = this.props.loading ? 'loading...' : this.props.title;
return (
<div>
<input readOnly={true} value={title} />
</div>
);
}
}
export namespace LasarTitle {
export interface Props {
title: string;
loading: boolean;
};
}
由于名称空间和类的名称相同,它们将被合并。合并将要做的一件事是,在运行时只有一个对象代表组合的类命名空间。出于实现原因,这种合并要求先创建类对象,然后再向其添加名称空间成员。
修改
如果名称空间仅包含类型,则不会应用此规则,如果包含代码(例如函数或变量声明),则将应用此规则。样板起作用,因为它不包含任何代码。虽然不明显,但您的命名空间确实包含代码,接口末尾的;
将被转换为空的JS语句,因此该规则得以执行。
更好的解决方案是删除;
import * as React from 'react';
import { connect } from 'react-redux';
import { RootState } from 'app/reducers';
export namespace LasarTitle {
export interface Props {
title: string;
loading: boolean;
}
};
@connect(
(state: RootState): LasarTitle.Props => {
return { title: state.title, loading: state.loading };
},
() => { }
)
export class LasarTitle extends React.Component<LasarTitle.Props> {
static defaultProps: Partial<LasarTitle.Props> = {
title: ''
};
constructor(props: LasarTitle.Props, context?: any) {
super(props, context);
}
render() {
const title = this.props.loading ? 'loading...' : this.props.title;
return (
<div>
<input readOnly={true} value={title} />
</div>
);
}
}