代码之家  ›  专栏  ›  技术社区  ›  Lars Holdgaard

如何在“this”中将值设置为未定义。“在构造函数内”状态?

  •  1
  • Lars Holdgaard  · 技术社区  · 8 年前

    我想要一个对象, CreditData ,在启动应用程序时未定义。首先,当我提交表单时,它是否应该设置数据(它将调用一个返回数据的API)。

    然而,根据我的Typescript,我必须设置 this.state 在构造函数内部。

    如果我做了以下事情: this.state = { loading: false, query: '', creditData: null }; ,我得到“ Type 'null' is not assignable to type CreditData' (与未定义的错误相同)。

    我如何等待分配任务 creditData 提交之前的值?

    import * as React from 'react';
    import { RouteComponentProps } from 'react-router';
    
    interface CompanySearchState {
        loading: boolean;
        query: string;
        creditData: CreditData
    }
    
    export class CompanySearch extends React.Component<RouteComponentProps<{}>, CompanySearchState> {
        constructor() {
            super();
            this.state = { loading: false, query: '', creditData: null };
        }
    
        public render() {
            return <div>
                <h1>Search company</h1>
    
                <div className='form-group'>
                    <input type='text' className='form-control' value={this.state.query} onChange={this.handleChange} />
                </div>
    
                <button onClick={() => { this.searchVat() } }>Search</button>
            </div>;
        }
    
        handleChange(evt:any) {
            this.setState({ query: evt.target.value });
        }
    
        searchVat() {
            alert('abe');
        }
    
    }
    
    interface CreditData {
        Description: string;
        Rating: number;
    }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   kingdaro    8 年前

    正如错误所述, null undefined 无法分配给未写入以接受它们的类型。因此,您有两种解决方案:

    // 1. My personal recommendation, define an initial value for creditData
    this.state = {
      loading: false,
      query: '',
      creditData: { description: '', rating: 0 }
    }
    
    // 2. Make creditData optional in your interface (and initialize with undefined instead of null)
    // This is useful if you want to differentiate states
    // between whether or not you have the data, or if there is no useful default value.
    interface CompanySearchState {
        loading: boolean;
        query: string;
        creditData?: CreditData
    }