期望在React JS中返回此函数array-callback-return末尾的值

时间:2017-04-28 17:02:38

标签: reactjs



render() {

        const rowLeft = [];
        const rowRight = [];
        let a = this.props.ntn;
        

       Object.keys(this.props.ntn).map((keyName, keyIndex) =>{

        if (keyName === "_id" || keyName === "name" || keyName === "description" || keyName === "instant" || keyName === "active") {
                  if (keyName === "beacon" || keyName === "group") {

            return rowLeft.push(<InfoRow notification={keyName} notificationValue={a[keyName].name.toString()} key={keyIndex}/>)
          } 

        else if (a[keyName].offers) {

            return rowLeft.push(<InfoRow notification={keyName} notificationValue={a[keyName].offers.toString()} key={keyIndex}/>)
          }

          else {

            return rowLeft.push(<InfoRow notification={keyName} notificationValue={a[keyName].toString()} key={keyIndex}/>)
         }}
       
       });

       Object.keys(this.props.ntn).map((keyName, keyIndex) =>{

        if (keyName === "levelType" || keyName === "triggeringEvents" || keyName === "type" || keyName === "beacon" || keyName === "inbox") {
                  if (keyName === "beacon" || keyName === "group") {

            return rowRight.push(<InfoRow notification={keyName} notificationValue={a[keyName].name.toString()} key={keyIndex}/>)
          } 

        else if (a[keyName].offers) {

            return rowRight.push(<InfoRow notification={keyName} notificationValue={a[keyName].offers.toString()} key={keyIndex}/>)
          }

          else {

            return rowRight.push(<InfoRow notification={keyName} notificationValue={a[keyName].toString()} key={keyIndex}/>)
         }}
       
       });

        return (
&#13;
&#13;
&#13;

我做了这样的事情 实际上,我正在获取值并显示页面上的所有详细信息 现在是什么东西我得到了这个警告 &#34;期望在React JS&#34;中的函数array-callback-return结束时返回一个值。 有解决方案吗怎么处理呢?

1 个答案:

答案 0 :(得分:9)

TLDR :最简单的解决方法是使用Object.keys(this.props.ntn).forEach代替.map,并使所有return rowLeft.pushrowLeft.push

答案很长

ESLint array-callback-return警告可确保您始终从mapfilterreduce等方法返回值。您没有首先在if中返回具有以下格式的值:

if condition1 {
   if condition2 {
      return
   }
   // here you are missing a return
}
else if ...

但是,您没有正确使用map。您应该使用forEach

当然,您的代码可以使用map重写,请考虑:

const {ntn} = this.props;

const rowLeft = Object.keys(ntn).map((keyName, keyIndex) => {
   const value = ntn[keyName];
   let notificationValue;   

   if (['_id', 'name', 'description', 'instant', 'active', 'beacon', 'group'].includes(keyName) {
       notificationValue = value.name.toString();
   } else if (value.offers) {
       notificationValue = value.offers.toString();
   } else {
       notificationValue = value.toString();
   }

   return (
      <InfoRow notification={keyName} notificationValue={notificationValue} key={keyIndex}/>
   );
});

另请注意,在您的示例中,第一个条件永远不会执行,因为它需要keyName一次两个值。我用一个条件取而代之,我想这就是你想要的。