Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React Typescript-Math.random即使设置了最小值和最大值,也会给出错误的结果_Reactjs_Typescript_Random_React Hooks_Local Storage - Fatal编程技术网

Reactjs React Typescript-Math.random即使设置了最小值和最大值,也会给出错误的结果

Reactjs React Typescript-Math.random即使设置了最小值和最大值,也会给出错误的结果,reactjs,typescript,random,react-hooks,local-storage,Reactjs,Typescript,Random,React Hooks,Local Storage,主TSX文件 const [minNumber, setMinNumber] = useLocalStorage('minRange', 1); const [maxNumber, setMaxNumber] = useLocalStorage('maxRange', 10); 本地存储挂钩: import { useState } from 'react'; export function useLocalStorage(key, defaultValue) { cons

主TSX文件

  const [minNumber, setMinNumber] = useLocalStorage('minRange', 1);
  const [maxNumber, setMaxNumber] = useLocalStorage('maxRange', 10);

本地存储挂钩:

import { useState } from 'react';

export function useLocalStorage(key, defaultValue) {
    const getInitialValue = () => localStorage.getItem(key) ?? defaultValue;
    const [value, setValue] = useState(getInitialValue);
    const setAndStoreValue = (newValue) => {
        if (newValue !== '') {
            setValue(newValue);
            localStorage.setItem(key, newValue)
        }
    }
    return [value, setAndStoreValue];
};
来演示这个问题。我已经创建了一个codesandbox链接:

如何重新创建问题:

import { useState } from 'react';

export function useLocalStorage(key, defaultValue) {
    const getInitialValue = () => localStorage.getItem(key) ?? defaultValue;
    const [value, setValue] = useState(getInitialValue);
    const setAndStoreValue = (newValue) => {
        if (newValue !== '') {
            setValue(newValue);
            localStorage.setItem(key, newValue)
        }
    }
    return [value, setAndStoreValue];
};
  • 默认情况下,minValue为1,maxValue为10
  • 将最小值设置为8,最大值设置为9(单击codesandbox中的“更改最小值和最大值”按钮)
  • 运行getRandomNumber()函数<代码>输出:8或9-有效!(单击codesandbox中的“新建随机数”按钮)
  • 刷新页面,您将获得存储在本地存储器中的数据,最小值为8,最大值为9
  • 运行getRandomNumber()函数<代码>输出0或1-输出错误!(单击codesandbox中的“新建随机数”按钮)
  • 问题是因为最小值和最大值之间的差值是2,所以它给出0和1。如果最小值为8,最大值为10,则输出0、1或2

我似乎不明白为什么会发生这种情况,因为如果我再次设置最小值和最大值,然后重新运行随机函数,效果会很好。我还想指出,在这两种情况下,console.log都输出
min:8 max:9
,因此本地存储似乎正在正确加载值。这很奇怪。

问题可以归结为:

const minNumber='8';
常量maxNumber='9';
常量getRandomNumber=()=>{
console.log(“min:+minNumber+”max:+maxNumber);
console.log('part',maxNumber-minNumber+1);
const result=Math.random()*2+'8';
控制台日志(结果);
};
getRandomNumber()