reactjs - 如果在 React Return() 中的 .map() 中带有表达式的语句
问题描述
我相信我遇到的问题是因为我的 map 函数在 react 的 return 方法中。这不可能吗?
需要发生的是我正在通过调查数据进行映射。我需要平均每个列。所以我要添加 column1 + column2 + column3,然后需要除以给出的响应数。我不能只除以 3,因为有些人将其中一个答案留空。所以我想出了下面的代码,但它给了我这个错误:Expected an assignment or function call and instead saw an expression
render() {
return (
<Jumbotron className="text-dark">
<Div>
<Row>
<Col>
<Table striped bordered>
<thead>
<th>Client</th>
<th>Name</th>
<th>Score: Consulting</th>
<th>Score: Talent</th>
</thead>
<tbody>
{
this.state.surveyData.map((client) => {
let consultingScoreDiv = 0;
const consultingScore = client.value1 + client.value2 + client.value3;
if (client.value1 !== ""){ consultingScoreDiv++ };
if (client.value2 !== ""){ consultingScoreDiv++ };
if (client.value3 !== ""){ consultingScoreDiv++ };
<tr key = { client.id } >
<td>{client.orgName}</td>
<td>{client.name}</td>
<td>{consultingScore/consultingScoreDiv}</td>
</tr>
}
)
}
</tbody>
</Table>
</Col>
</Row>
</Div>
</Jumbotron>
)
}
解决方案
You had few issue:
- You are missing the a
return
in yourmap
. - You check for empty string, instead of
undefined
ortypeof
- you calculated the total even if there was no value there.
- You did not check division by 0.
Here's how it should look like:
{this.state.surveyData.map((client) => {
let consultingScoreDiv = 0;
let consultingScore = 0;
if (typeof client.value1 === "number") {
consultingScoreDiv++;
consultingScore += client.value1;
}
if (typeof client.value2 === "number") {
consultingScoreDiv++;
consultingScore += client.value2;
}
if (typeof client.value3 === "number") {
consultingScoreDiv++;
consultingScore += client.value3;
}
return (
<tr key={client.id}>
<td>{client.orgName}</td>
<td>{client.name}</td>
<td>
{consultingScoreDiv > 0
? consultingScore / consultingScoreDiv
: 0}
</td>
</tr>
);
})}
推荐阅读
- javascript - SVG 用 JS 附加到 DOM 但没有视觉呈现
- python-3.x - 在 python 中使用函数式编程列出字典
- android - Android CoordinatorLayout 以编程方式触发 Hide-Bottom-on-Scroll 行为
- android - 无法获取电话号码以在谷歌操作(nodeJs)中启动自动呼叫
- python - 在使用数据框的目标函数上使用 Scipy 的蛮力优化
- bash - 在bash中将较小的数字除以较大的数字
- svelte - Sveltekit 有预览模式吗?
- proxy-server - 用一个mini pc和10个加密狗可以搭建一个移动代理服务器吗?
- javascript - 引导导航链接在 reactjs 中不起作用
- matlab - 有没有办法使用matlab中的sum()函数对矩阵中提取的位置求和