在像下面的代码片段这样的情况下,我应该如何处理NaN
状态类型在哪里number
。
服务器发送一个对象数组:
interface MyInterface {id:number, amount:number, score:number}
// The received data is of type MyInterface[]
所以这里的空输入将导致NaN
, Warning: Received NaN for the
value 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>
))}
</>
);
}