【问题标题】:React with TypeScript, prompt() return value与 TypeScript 反应,prompt() 返回值
【发布时间】:2021-11-23 17:54:43
【问题描述】:

当我想更新我的 State 时,TypesScript 显示错误

TyepScript 在getApiKey 函数内的setapiKey(prompValue); 中用红色下划线prompValue,错误为:

'string | 类型的参数null' 不能分配给“SetStateAction”类型的参数。 类型 'null' 不可分配给类型 'SetStateAction'.ts(2345)

这是什么问题,我该如何解决?

function App() {

  const [apiKey, setapiKey] = useState('');

  const getApiKey = () => {
    const prompValue = prompt('Enter API Key');
    setapiKey(prompValue);
  }

  return (
    <div className="App">
      <h1>App</h1>
      <button onClick={getApiKey}>API</button>
      <p>{apiKey}</p>
    </div>
  );
}

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    如答案中所述,prompt 返回string(如果用户尝试写一些东西)和null 如果用户关闭提示而不输入任何内容。

    所以,Typescript 会关心promptValue。它假定您的值的类型是 stringnull 之一。

    因为promptValue 是一个字符串,所以没有问题,因为您将apiKey 值定义为一个在useState 中初始化为空字符串的字符串。

    但是在从 promptValue 返回 null 的情况下,打字稿会阻止您将 null 值放入定义为字符串的 apiKey 中。

    【讨论】:

      【解决方案2】:

      其实,这就是打字稿的强大之处。 prompt 返回string | null.

      你应该处理用户取消提示对话框的情况,以减少错误。

      function App() {
      
        const [apiKey, setapiKey] = useState('');
      
        const getApiKey = () => {
          const prompValue = prompt('Enter API Key');
          if(prompValue === null) {
            // do what ever you want when the user cancel the prompt
          }
          else {
            setapiKey(prompValue);
          }
        }
      
        return (
          <div className="App">
            <h1>App</h1>
            <button onClick={getApiKey}>API</button>
            <p>{apiKey}</p>
          </div>
        );
      }
      

      【讨论】:

      • 简洁明了的解释。
      • 谢谢!!!我有 5 天的时间用 TypeScript-React 做一个项目,这是我第一次使用 TypeScript……(我想我会提出很多问题……:))
      • 是个不错的选择。 TS 会在有点卡住的情况下获得很多经验。 ?
      猜你喜欢
      • 2018-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-14
      • 2020-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多