从Promise <String>打字稿中将状态设置为字符串?

时间:2020-06-03 09:38:22

标签: reactjs typescript

我正在尝试设置名为“ apiResponse”的变量的状态。但是,打字稿一直向我抱怨说,我在.then((res) => this.setState({ apiResponse: res,})坚持以下错误:

类型'()=> Promise'缺少类型'String'的以下属性:charAt,charCodeAt,concat,indexOf和另外41个。

是否有修复程序?

我已经查找了类似的stackOverflow问题,但似乎都没有解决这个问题。也许他们有,但我不知道如何解释它,因为我对打字稿还比较陌生。感谢您的帮助

interface IProps {}

interface IState {
  apiResponse: String;
}

class App extends React.Component<IProps, IState> {
  state: IState;

  constructor(props: IProps) {
    super(props);
    this.state = {
      apiResponse: "",
    };
  }

   callAPI = () => {
    fetch("http://localhost:9000/testAPI")
      .then((res) => res.text)
      .then((res) =>
        this.setState({
          apiResponse: res,
        })
      )
      .catch((err) => err);
  };

  componentDidMount() {
    this.callAPI;
  }

  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.tsx</code> and save to reload.
          </p>
        </header>
        <p className="App-intro">{this.state.apiResponse}</p>
      </div>
    );
  }
}

1 个答案:

答案 0 :(得分:0)

调用函数和正确提供诺言有一些问题。

this.callAPI替换为this.callAPI()

也将res.text替换为res.text()