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

Piy*_*ush 5 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 (
Run Code Online (Sandbox Code Playgroud)

我做了类似这样的事情,实际上我正在获取值并在页面上显示所有细节现在是什么东西我得到这个警告"预期在React JS的函数数组末尾返回一个值 - 回调 - 返回"任何解决方案?怎么处理呢?

Sul*_*han 9

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

答案很长:

该ESLint 阵列回调返回警告确保您始终返回从类似方法的值map,filterreduce.您没有首先返回if具有以下形式的值:

if condition1 {
   if condition2 {
      return
   }
   // here you are missing a return
}
else if ...
Run Code Online (Sandbox Code Playgroud)

但是,您没有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}/>
   );
});
Run Code Online (Sandbox Code Playgroud)

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