如何解决如何在 useState Hook 中将字符串转换为数字?
我正在尝试在输入数据之前将数据从字符串转换为数字,以便稍后对数据进行数学计算。
我尝试在 useState 挂钩中使用 parseInt,但收到以下错误: ReferenceError: 初始化前无法访问词法声明“score”
import React,{ Fragment,useState } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { addGame } from '../../actions/game';
const GameInput = ({ addGame }) => {
const [formData,setFormData] = useState({
score: parseInt(score,10),strikes: parseInt(strikes,spares: parseInt(spares,openFrames: parseInt(openFrames,});
// Destructure formData
const { score,strikes,spares,openFrames } = formData;
// Input Method to change state
const onChange = (e) =>
setFormData({ ...formData,[e.target.name]: e.target.value });
// onSubmit Form Method
const onSubmit = (e) => {
e.preventDefault();
addGame(formData);
};
return (
<Fragment>
<h1>Record Your Stats</h1>
<form onSubmit={(e) => onSubmit(e)}>
<div>
<input
type='text'
placeholder='Score'
name='score'
value={score}
onChange={(e) => onChange(e)}
/>
<small>Your score for this game</small>
</div>
<div>
<input
type='text'
placeholder='Stikes'
name='strikes'
value={strikes}
onChange={(e) => onChange(e)}
/>
<small># of Strikes hit this game</small>
</div>
<div>
<input
type='text'
placeholder='Spares'
name='spares'
value={spares}
onChange={(e) => onChange(e)}
/>
<small># of Spares hit this game</small>
</div>
<div>
<input
type='text'
placeholder='Open Frames'
name='openFrames'
value={openFrames}
onChange={(e) => onChange(e)}
/>
<small># of frames with pins left standing</small>
</div>
<input type='submit' />
<Link className='btn btn-light my-1' to='/profile'>
Back to Profile
</Link>
</form>
</Fragment>
);
};
GameInput.propTypes = {
addGame: PropTypes.func.isRequired,};
export default connect(null,{ addGame })(GameInput);
解决方法
状态尚未定义,因此无法访问。您正在设置初始状态,因此只需使用您想要的类型声明它。 score
、strikes
、spares
和 openFrames
尚未声明或定义,因此无法使用。
似乎您真的想在更新状态时将输入字符串解析回数字类型。为了保持您的状态不变,您可以/应该在您的 onChange
处理程序中进行此转换。
// Input Method to change state
const onChange = (e) => {
const { name,value } = e.target;
setFormData({ ...formData,[name]: parseInt(value,10) }); // Or Number(value)
};
提供有效的初始状态。
const [formData,setFormData] = useState({
score: 0,strikes: 0,spares: 0,openFrames: 0,});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。