[英]So how can I sum all the values in all objects in an array which is coming from react redux?
This is react redux reducer file where numbers array is:这是反应 redux 减速器文件,其中数字数组是:
const initialState = {
numbers: [ { name: 'max', num: 3 }, { name: 'jack', num: 2 } ]
}
This is how I want to sum all the num values in all objects in numbers array which is recieved from react redux state reducer file这就是我想对从反应 redux state 减速器文件收到的 numbers 数组中所有对象中的所有 num 值求和的方式
In component:在组件中:
useEffect(() => {
const total = props.numbers.reduce((prev, current) => {
return prev + current.num, 0;
});
console.log(total);
console.log(props.numbers);
}, []);
This is the console logs from useEffect:这是来自 useEffect 的控制台日志:
0
(2) [{…}, {…}]
0: {name: "max", num: 3}
1: {name: "jack", num: 2}
length: 2
__proto__: Array(0)
The total const is just 0 and its not working.总 const 只是 0 并且它不起作用。
So how can I sum all the num values in all objects in an array which is coming from redux reducer file??那么如何将来自 redux 减速器文件的数组中所有对象中的所有 num 值相加?
The , 0
should be the second argument to reduce
, not in the return
: , 0
应该是reduce
的第二个参数,而不是return
:
const total = props.numbers.reduce((prev, current) => {
return prev + current.num;
}, 0);
you need to fix reduce:你需要修复减少:
const total = props.numbers.reduce((prev, current) => {
return prev + current.num;
}, 0);
You can also use map function您也可以使用map function
sum = 0;
props.numbers.map(n => {
sum+= n.num;
})
You need to provide an initial value for prev
, as the second param of reduce
.您需要为prev
提供一个初始值,作为reduce
的第二个参数。 If its not provided then during the first run, first param of callback function is the first element of array and second param of callback function is the second element of array.如果未提供,则在第一次运行期间,回调 function 的第一个参数是数组的第一个元素,回调 function 的第二个参数是数组的第二个元素。 Then the return value is passed to the first param and the next element is the second value.然后将返回值传递给第一个参数,下一个元素是第二个值。
So, to add I have added 0
as the initial value.因此,要添加,我添加了0
作为初始值。
const numbers = [ { name: 'max', num: 3 }, { name: 'jack', num: 2 } ] const total = numbers.reduce((prev, { num }) => { return prev + num }, 0) console.log(total)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.