【问题标题】:TypeScript: Object is possibly 'null'TypeScript:对象可能是“空”
【发布时间】:2019-12-10 14:46:56
【问题描述】:

我正在尝试将 react 项目转换为 TypeScript。下面的代码是一个输入字段,用于计算输入的字符数。

在 renderCharactersLeft 函数中出现以下错误:

这并不让我感到惊讶,因为默认状态 'charsLeft' 设置为 null,但我想知道您将如何绕过或在 TypeScript 中解决此消息?

import React from "react";

interface CharCountInputProps {
  value: string;
  type: string;
  name: string;
  maxChars: number;
  onChange: any;
}

interface CharCountInputState {}

class CharCountInput extends React.Component<
  CharCountInputProps,
  CharCountInputState
> {
  state = {
    charsLeft: null
  };

  componentDidMount() {
    this.handleCharCount(this.props.value);
  }

  handleCharCount = (value: string) => {
    console.log(value);
    const { maxChars } = this.props;
    const charCount = value.length;
    const charsLeft = maxChars - charCount;
    this.setState({ charsLeft });
  };

  changeHandler = (event: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({ [event.target.name]: event.target.value } as Pick<
      CharCountInputState,
      keyof CharCountInputState
    >);
    this.handleCharCount(event.target.value);
    this.props.onChange(event);
  };

  renderCharactersLeft = () => {
    const { charsLeft } = this.state;

    let content;
    if (charsLeft >= 0) {
      content = <span>{`characters left: ${charsLeft}`}</span>;
    } else if (charsLeft != null && charsLeft < 0) {
      const string = charsLeft.toString().substring(1);
      content = <span>{`too many characters: ${string}`}</span>;
    } else {
      content = null;
    }
    return content;
  };

  render() {
    const { value, type, name } = this.props;

    return (
      <>
        <input
          onChange={this.changeHandler}
          value={value}
          type={type}
          name={name}
        />
        {this.renderCharactersLeft()}
      </>
    );
  }
}

export default CharCountInput;

【问题讨论】:

  • 你不能做类似charsLeft &amp;&amp; charsLeft &gt;= 0的事情
  • 嗯,是的,我试过了。然后我在 && (charsLeft >= 0) 之后的下一个 charsLeft 上得到错误
  • charsLeft 初始状态为空的原因是什么? 0 的初始状态是否更合适?
  • 添加该行时出现什么错误?
  • 是否需要null?你不能把它设置为this.props.maxChars吗?

标签: javascript reactjs typescript


【解决方案1】:

你可以像这样在你的 if 语句中添加一个空检查:

if (charsLeft !== null &amp;&amp; charsLeft &gt;= 0) {

或者将 charsLeft 的初始状态设置为 null 以外的其他值(例如,您的道具中的 maxChars)

【讨论】:

  • 将 != 更改为 !== 以便检查类型和值。除非您知道自己在做什么!否则永远不要使用 !=。
  • 哈哈,太明显了,我看不出来!将初始状态设置为我的 maxChars 解决了这个问题。谢谢!
猜你喜欢
  • 2022-01-14
  • 1970-01-01
  • 2019-11-10
  • 2021-12-01
  • 1970-01-01
  • 2019-11-16
  • 2019-10-22
  • 1970-01-01
  • 2018-08-06
相关资源
最近更新 更多