当我在Angular项目中使用代码时,代码正在工作,然后我决定移至React,代码工作不正确。
import React, {Component} from 'react'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
class SomeComponent extends Component {
componentWillMount() {
this.props.someFunc()
if ( this.props.userLogin[0].isUserLogin === false ) {
/// here i want to redirect to another route
}
}
render() {
return(
<div>Some Content</div>
)
}
}
const mapStateToProps = state => ({
userLogin: state.UserLogin,
})
function mapDispatchToProps(dispatch) {
return {
someFunc: bindActionCreators(someAction, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SomeComponent)
控制台日志的输出为class A {
constructor(...parts: Partial<A>[]) {
Object.assign(this, ...parts);
}
}
class B extends A {
id: string;
constructor(...parts: Partial<B>[]) {
super(...parts);
}
}
const a = new B({ id: '123' });
console.log(a);
,我希望它为B {id: undefined}
这是tsconfig:
B {id: '123'}
这里是版本:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": false,
"allowSyntheticDefaultImports": true,
"forceConsistentCasingInFileNames": true,
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "preserve",
"strict": false
},
"include": [
"src"
]
}
复制的最小步骤:
已更新:
我最终使用以下解决方案:
+ @types/jest@24.0.9
+ react-scripts@2.1.5
+ @types/react-dom@16.8.2
+ react@16.8.3
+ @types/react@16.8.6
+ typescript@3.3.3333
+ react-dom@16.8.3
+ @types/node@11.10.4
+ create-react-app@2.1.5
答案 0 :(得分:2)
这是known problem。它在TypeScript中不存在。原因是create-react-app TypeScript支持使用TypeScript进行类型检查,并使用Babel进行翻译。
此TS代码
class B extends A {
id: string;
...
}
已转换为此ES。下一个代码:
class B extends A {
id;
...
}
根据class field proposal,未分配的id
字段将转换为this.id = undefined
。
为了使用与TypeScript兼容的行为,需要更改设置以使用@babel/plugin-transform-typescript
转换为ES5或使用TypeScript代替Babel,例如。不推荐使用的react-scripts-ts
。
答案 1 :(得分:0)
两个可能的解决方法:
export interface Ctor<T> { new(...parts: Partial<T>[]): T; } export class Factory { public static Get<T extends object>(ctor: Ctor<T>, ...props: Partial<T>[]): T { const res = new ctor(); Object.assign(res, ...props); return res; } }