当调度值为 int 的 reducer 时返回 NaN

returning NaN when dispatch reducer with a value of int

我需要有关此 react-redux 代码的帮助。有一个输入字段,它接受数字并将它们添加到上面的计数器中。如果输入不是数字,我想将计数器重新设置为 0,但是当我键入任何不同于 int 的字符时,它将计数器设置为 NaN。我试图从 reducer 和一个单独的函数中转换状态值,但都没有用。


//counterSlice.js

import { createSlice } from "@reduxjs/toolkit";

export const counterSlice = createSlice({
  name: "counter",
  initialState: {
    value: 0,
  },
  reducers: {
    increment: (state) => {
      // Redux Toolkit allows us to write "mutating" logic in reducers. It
      // doesn't actually mutate the state because it uses the Immer library,
      // which detects changes to a "draft state" and produces a brand new
      // immutable state based off those changes
      state.value += 1;
    },
    decrement: (state) => {
      state.value -= 1;
    },
    incrementByAmount: (state, action) => {
      state.value += action.payload;
    },
    reset: (state) => {
      
      state.value = 0;

    },
  },
});

// Action creators are generated for each case reducer function
export const { increment, decrement, incrementByAmount, reset } =
  counterSlice.actions;

export default counterSlice.reducer;



//Counter.js

import React, { useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { decrement, increment, incrementByAmount, reset } from "./counterSlice";

export function Counter() {
  const count = useSelector((state) => state.counter.value);
  const dispatch = useDispatch();
  const [add, setAdd] = useState();

  const changeAdd = (e) => {
    e.preventDefault();

    if (isNaN(add)) {
      dispatch(reset());
    }

    dispatch(incrementByAmount(Number(add)));
    setAdd("");
  };

  return (
    <div>
      <div>
        <button
          aria-label="Increment value"
          onClick={() => dispatch(increment())}
        >
          Increment
        </button>

        <span>{count}</span>

        <button
          aria-label="Decrement value"
          onClick={() => dispatch(decrement())}
        >
          Decrement
        </button>

        <form onSubmit={changeAdd}>
          <input
            type="text"
            value={add}
            onChange={(e) => setAdd(e.target.value)}
          />
          <button type="submit">send</button>
        </form>
      </div>
    </div>
  );
}
export default Counter;

在检查它是否为 NaN 之前,您应该将值转换为数字:

if (isNaN(Number(add))) {

您应该在 if (isNaN(add)) 的末尾添加一个 return,否则您仍然会使用非数字值发送 incrementByValue