React类组件修改checkbox状态触发array-callback-return错误的原因?
问题:React类组件中map函数编译报错
array-callback-return 编译时出现如下错误:
Line 15:59: Array.prototype.map() expects a return value from arrow function array-callback-return
相关代码如下:
import React from "react"; class ItemList extends React.Component { constructor(props) { super(props); this.state = { items: props.items } } toggleCompleted = (position) => { const updatedItems = this.state.items.map((item, idx) => { position === idx ? {...item, completed: !item.completed} : item // 报错行 }) this.setState({ items: updatedItems }) } render() { return( <div className="col-12 col-lg-8 mx-auto"> <h3 className="h3">Tasks</h3> {this.state.items.length > 0 && <table className="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Title</th> <th scope="col">Description</th> <th scope="col">Completed</th> </tr> </thead> <tbody> {this.state.items.map((item, idx) => { return ( <tr key={idx+1}> <th scope="row">{idx+1}</th> <td>{item.title}</td> <td>{item.description}</td> <td> <input id={"completed".concat(idx)} className="form-check-input" type="checkbox" checked={item.completed} onChange={() => {this.toggleCompleted(idx)}}/> </td> </tr> ); })} </tbody> </table> } </div> ) } } export default ItemList;
错误原因
问题出在toggleCompleted方法里的map回调函数:
你给箭头函数加了大括号{}包裹函数体,但没有用return语句返回三元运算的结果。
Array.prototype.map()要求每一次迭代的回调函数都必须返回一个值,用来生成新数组的元素。当箭头函数使用大括号时,函数体不会自动返回表达式结果,必须显式写return;如果不用大括号,单行表达式会自动作为返回值。
修复方法
有两种方式可以解决:
方式1:去掉大括号,让表达式自动返回
toggleCompleted = (position) => { const updatedItems = this.state.items.map((item, idx) => position === idx ? {...item, completed: !item.completed} : item ) this.setState({ items: updatedItems }) }
方式2:保留大括号,添加显式return
toggleCompleted = (position) => { const updatedItems = this.state.items.map((item, idx) => { return position === idx ? {...item, completed: !item.completed} : item }) this.setState({ items: updatedItems }) }
内容的提问来源于stack exchange,提问作者be-1
相关产品推荐
相关产品推荐

