gpt4 book ai didi

javascript - 总结 React Prop 中对象数组中的所有 'score' 值

转载 作者:行者123 更新时间:2023-11-30 09:16:19 25 4
gpt4 key购买 nike

抱歉标题绕口令,但这是一个非常具体的问题。

目前我有一系列对象被 Prop 穿过。我正在尝试将所有“分数”值汇总在一起并将其显示在我的应用中。

对象看起来像这样:

[{'id': '1', 'score': '10'}, {'id': '2', 'score': '20'}, {'id': '3', 'score': '35'}]

在应用程序内部,它被调用如下:

state = { 
content: this.props.navigation.getParam('content', false),
}

scoreCount = () => {
const content = this.state.content;

if (content) {
return content.reduce((prev, current) => prev.score + current.score);
} else {
return false;
}

render() {

const score = this.scoreCount()

return (
<View>
<Text>Score:</Text>
{ score ?
<Text>
{ score }
</Text> :
<Text>
0
</Text>
}
</View>
)}

返回时显示'undefined35'

我知道这与通话时 Prop 不可用有关,但我不确定如何将分数正确地返回到 View

非常感谢任何帮助

最佳答案

您似乎正在尝试添加字符串,因为 score 的值为 '10' 等等,它们都是 string 。所以你可以使用一元运算符将其转换为数字。其次,我认为 prev.score 在第一次添加时会是一个问题,因为没有 score 键。所以在 reduce 中传递的 0 将被视为第一个元素

let content = [{
'id': '1',
'score': '10'
}, {
'id': '2',
'score': '20'
}, {
'id': '3',
'score': '35'
}];

let sum = content.reduce(function(prev, current) {
return prev + +current.score
}, 0);
console.log(sum)

关于javascript - 总结 React Prop 中对象数组中的所有 'score' 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54862549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com