reactjs - 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;
}
};
任何帮助,将不胜感激。
解决方案
您可以创建一个函数,该函数采用特定的权重值并将百分比值数组映射到该权重的百分比数组。
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);
推荐阅读
- c# - 异步任务使程序挂起
- oracle - 将 Oracle 业务智能报告 (OBIE) 连接到 Power BI
- c++ - 如何扩展可变参数模板类
- python - 如果集合包含相同的元素,则合并集合字典中的集合
- mongodb - 合并两个 Mongo 集群
- c++ - 使用柯南安装的 GoogleTest 库编译程序失败
- laravel - 雄辩的关系 - hasOneThrough 关系
- javascript - 每次用户点击页面时,页面标题都会改变颜色
- javascript - 保存数据时出错“无法读取未定义的属性‘get’”
- swift - 根据 contenView 大小以编程方式调整滚动视图的大小 [Swift]