数组映射没有返回值的反应

问题描述 投票:0回答:2

我有以下功能

  churnModel = () => {
        if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
          return("N/A")
        } else {
          this.props.churnModel.map((churn) => {
            if (churn === undefined || churn.length === 0) {
              return("N/A")
            } else {
              return(churn.map((model) => {
                this.service(model.scoreModelId)
              }))
            }
          })
        }
  };

this.service函数看起来像这样......

service(e) {
  switch(e.toString().toLowerCase()) {
    case "in":
      return <span>in</span>
    case "rpt_callr":
      return <span>repeat</span>
    default:
      return <span>na</span>
  }
}

我希望在这里显示结果:

<div className="riskScore">{this.churnModel()}</div>

什么都没有显示,但是当我放入日志时,会打印出来。

这里发生了什么?

javascript reactjs
2个回答
1
投票

你需要在return.this.props.churnModel.map之前放置this.service(model.scoreModelId)

  1. 如果没有任何东西返回,function将返回undefined
  2. map()进行回调并将数组的每个元素更改为该回调的return值。如果你不return什么所有元素将是undefined

你也可以通过删除return摆脱this.service(model.scoreModelId)之前的{}。就像这样。

return(churn.map((model) => this.service(model.scoreModelId)))

这是代码

churnModel = () => {
        if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
          return("N/A")
        } else {
          return this.props.churnModel.map((churn) => {
            if (churn === undefined || churn.length === 0) {
              return("N/A")
            } else {
              return(churn.map((model) => {
                return this.service(model.scoreModelId)
              }))
            }
          })
        }
  };

0
投票

你必须在几行中使用return语句:

 churnModel = () => {
            if (this.props.churnModel === undefined || this.props.churnModel.length === 0) {
              return("N/A")
            } else {
              return this.props.churnModel.map((churn) => {
                if (churn === undefined || churn.length === 0) {
                  return("N/A")
                } else {
                  return(churn.map((model) => {
                    return this.service(model.scoreModelId)
                  }))
                }
              })
            }
      };

你为什么需要回来?这是因为你正在使用curly braces

© www.soinside.com 2019 - 2024. All rights reserved.