React中return内.map()含表达式报Expected an assignment错误如何解决
问题解答
基础问题确认
在React的render方法return语句中使用map函数遍历渲染列表是完全合法且常用的操作,你遇到的报错属于基础语法错误,和map本身的使用场景无关。
报错原因
你在map的回调里使用了带花括号的箭头函数写法,这种写法下函数体内部必须显式使用return语句返回需要渲染的JSX元素。你当前代码中计算完分数后直接写了<tr>标签,没有添加return声明,JS解析器识别到这段JSX是没有被使用的表达式,因此抛出对应报错。
另外你的逻辑还存在两个可优化的边界问题:
- 如果三个value值全部为空,
consultingScoreDiv会等于0,直接计算除法会得到NaN - 如果value是字符串类型的得分,直接相加会触发字符串拼接而非数值计算,需要先做类型转换
修正后代码
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; let consultingScore = 0; // 仅累加非空项,同时做类型转换避免字符串拼接 if (client.value1 !== "") { consultingScore += Number(client.value1); consultingScoreDiv++; } if (client.value2 !== "") { consultingScore += Number(client.value2); consultingScoreDiv++; } if (client.value3 !== "") { consultingScore += Number(client.value3); consultingScoreDiv++; } // 显式return需要渲染的JSX元素 return ( <tr key={client.id}> <td>{client.orgName}</td> <td>{client.name}</td> <td>{consultingScoreDiv === 0 ? '-' : (consultingScore / consultingScoreDiv).toFixed(2)}</td> </tr> ) }) } </tbody> </Table> </Col> </Row> </Div> </Jumbotron> ) }
内容的提问来源于stack exchange,提问作者Adam Norton
相关产品推荐
相关产品推荐

