2

在像下面的代码片段这样的情况下,我应该如何处理NaN状态类型在哪里number

服务器发送一个对象数组:

interface MyInterface {id:number, amount:number, score:number}
// The received data is of type MyInterface[]

所以这里的空输入将导致NaN, Warning: Received NaN for thevalue attribute. If this is expected, cast the value to a string.

如果我检查条件 isNaN(parseInt(e.target.value)),我应该用什么更新状态?一般来说,在这种情况下,我怎么能有 empty input

const App:React.FC<Props>=(props:Props)=> {
  const [data, setData] = React.useState<MyInterface[]>(props.values);

  const handleChange = (e: ChangeEvent<HTMLInputElement>,id:number) => {
    const amount = parseInt(e.target.value, 10);
    const temp:MyInterface[] = data.map(d => d.id === id? {...d,amount} : d)
    setData(temp);
  };

  const upload = ()=> { /* POST the state array to server */}

  return (
      <>
        {data.map(d=> (
         <div>
           <input value={d.amount} onChange={handleChange} />
           <button onClick={upload}/>
         </div>
        ))}  
      </>
 );
}
4

1 回答 1

0

这真的很烦人。我们自己解决了这个问题,我能想出的唯一解决方案是阻止向用户显示这个特定的错误。

于 2021-05-07T14:22:59.617 回答