Reactjs 为什么我的号码似乎是React中的一个对象?
我的类定义如下:Reactjs 为什么我的号码似乎是React中的一个对象?,reactjs,Reactjs,我的类定义如下: class MyPage extends React.Component<MyPage Props, {startTypeValue: number}> { constructor(props: any) { super(props); this.state = { startTypeValue: 0 };... 这显示了我所期望的,{val:“0”} 现在,我通过执行DB调用来设置startTypeValue的值: await this.st
class MyPage extends React.Component<MyPage Props, {startTypeValue: number}> {
constructor(props: any) {
super(props);
this.state = { startTypeValue: 0 };...
这显示了我所期望的,{val:“0”}
现在,我通过执行DB调用来设置startTypeValue
的值:
await this.startTypeGetPromise(this.props.someval).then((ret) =>
this.setState({startTypeValue: ret}));
现在我再次显示startTypeValue
:
const aval=this.state.startTypeValue;
console.log( {aval});
它给出:aval:startType:1
。现在startType
是db变量的名称,所以这是我希望返回的,但是startTypeValue
被定义为number
,那么它为什么显示为这样呢?更重要的是,我如何将startTypeValue
设置为1而不是startType:1
?等待这个。startTypeGetPromise(this.props.someval)。然后((ret)=>
this.setState({startTypeValue:ret.startType}));
为什么首先命名变量xxxValue
?值
部分不会为名称添加任何有用的内容。每个变量都有一个值startType
是一个更合理的变量名。是的,这一点很公平!谢谢,但这给了我:属性'startType'在类型'number'上不存在。
@schoon这似乎是一个类型脚本错误。可能您的ret
被键入为一个数字
,但实际上它不是一个数字。请注意,typescript不进行运行时检查。您的承诺解析的值可能键入不正确。Typescript在运行时不强制执行任何类型,它只是声明并检查开发人员在编译时定义的预期类型,而不是实际类型。@trixn您是对的,谢谢。我将其设置为any,并根据俞淼的回答,它可以修复警告,但解决此问题的正确方法是定义一个与响应匹配的类型。因为现在您已经破坏了对响应的任何进一步类型检查。
const aval=this.state.startTypeValue;
console.log( {aval});