首页 > 解决方案 > React Redux 在映射状态后获取 NaN

问题描述

我在映射我的状态时遇到问题。我的状态包含一个对象数组,每个对象都有两个键:值对:

[
 {
  name: '',
  weight: 0
 }
]

我的问题是访问重量值。当我只有一个对象时,映射没有问题,我将 weight 的值作为一个数字。但是当我向状态添加第二个对象并映射两个对象的权重值时,我得到 NaN。地图的结果将进入百分比计算器,这就是我需要这些数字的原因。这是我的应用程序的屏幕截图,其中我只有一个对象: 在此处输入图像描述 这是我有两个对象的屏幕截图。我还在顶部的“One Rep Max”部分调用了 mapWeights,因此它同时显示了“300”和“400”。我打算解决这个问题。但这是我开始得到 NaN 的地方: 在此处输入图像描述 这是我调用 .map 的方式:

    const mapWeights = props.weight.map(value => parseInt(value.movementWeight));

这是我调用映射结果的地方:

  useEffect(() => {
        const arr = [];
        let percentage = 100;
        while (percentage > 50 ) {
            arr.push([percentage, (mapWeights * percentage) / 100]);
            percentage -= 5;
        }
        setResults(arr);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

如果您需要我的减速器:

const addMovementReducer = (state = [], action) => {
    switch (action.type) {
        case ADD_MOVEMENT: 
            return [ ...state, action.payload ];
        default:
            return state;
    }
};

任何帮助,将不胜感激。

标签: reactjsreduxmappingstateredux-form

解决方案


您可以创建一个函数,该函数采用特定的权重值并将百分比值数组映射到该权重的百分比数组。

const percentValues = [100, 95, 90, 85, 80, 75, 70, 65, 60, 55];

const computePercentages = (weight) =>
  percentValues.map((percent) => (weight * percent) / 100);

然后使用computePercentages要计算这些百分比数组的实用程序。

const data = [
  {
    name: "Bench",
    weight: 300
  },
  {
    name: "Squat",
    weight: 400
  }
];

const percentages = data.map((el) => {
  return computePercentages(el.weight);
});

const data = [
  {
    name: "Bench",
    weight: 300
  },
  {
    name: "Squat",
    weight: 400
  }
];

const percentValues = [100, 95, 90, 85, 80, 75, 70, 65, 60, 55];

const computePercentages = (weight) =>
  percentValues.map((percent) => (weight * percent) / 100);

const percentages = data.map((el) => {
  return computePercentages(el.weight);
});

console.log(percentages);

在 React 中,您可能更可能希望将原始数据与派生数据一起映射。为此,您可以将数据“合并”到一个易于映射到 JSX 的数组中。

const data = [
  {
    name: "Bench",
    weight: 300
  },
  {
    name: "Squat",
    weight: 400
  }
];

const percentValues = [100, 95, 90, 85, 80, 75, 70, 65, 60, 55];

const computePercentages = (weight) =>
  percentValues.map((percent) => (weight * percent) / 100);

const dataWithPercentages = data.map((el) => {
  return {
    ...el,
    percentages: computePercentages(el.weight),
  };
});

console.log(dataWithPercentages);


推荐阅读