javascript - 如何在 useState Hook 中将字符串转换为数字?

标签 javascript reactjs react-hooks use-state parseint

I am trying to convert data from a string to a number before it is inputted so that I can perform mathematical calculations on the data later.

I tried to use parseInt inside of my useState hook but I received the following error: ReferenceError: can't access lexical declaration 'score' before initialization

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, 10),
    spares: parseInt(spares, 10),
    openFrames: parseInt(openFrames, 10),
  });

  // 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);

最佳答案

状态尚未定义,因此无法访问。您正在设置初始状态,因此只需使用您想要的类型声明它即可。 scorestrikessparesopenFrames 尚未声明或定义,因此它们不能被使用。

似乎您真的想在更新状态时将输入字符串解析回数字类型。为了保持您的状态不变,您可以/应该在您的 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,
});

关于javascript - 如何在 useState Hook 中将字符串转换为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67271684/

相关文章:

javascript - 为什么我在使用 React-Web 时遇到这些错误

javascript - AngularJS 指令不更新 D3 圆包图表

javascript - 自动从nodejs和express中的文件夹中请求 "controllers"

javascript - react native onChange 事件的名称类型值未定义

android - React Native App 在启动时在 android 11 上崩溃而没有给出错误

javascript - 为 Material.io 设置环境的资源?

reactjs - 如何测试可以将html元素的引用传递给它的 react 钩子(Hook)

javascript - jQuery 获取当前元素 (x)html

javascript - 即使状态值没有变化也会渲染组件

javascript - Draft JS 编辑器在父组件更改其值时不更新其内容?