在React无状态组件中不能使用数组原型.find?

问题描述 投票:-1回答:1

我的应用正在呈现此组件:

<LabelTop orderNumber={order.id} shippingMethodName={getShippingMethod(order.shipping_lines)} customerName={order.billing.first_name + " " + order.billing.last_name}/>

getShippingMethod()是同一文件中的一个简单格式化程序。

const getShippingMethod = (shipping_lines) => {
  const metaObj = shipping_lines.find(meta => meta.method_title !== "")
  return metaObj.method_title
}

如果我重构将getShippingMethod()移动到组件本身,我会得到.find不是方法的错误。

export const LabelTop = props => {

const getShippingMethod = (shipping_lines) => {
  const metaObj = shipping_lines.find(meta => meta.method_title !== "")
  return metaObj.method_title
}

return (
  <div>
    <div>
      <img src={LogoIcon} alt="Logo"/>
      <div>{props.orderNumber}</div>
    </div>
    <div>
      <div><span>Method:</span> {getShippingMethod(props.shippingMethodName)}</div>
      <div><span>Customer:</span> {props.customerName}</div>
    </div>
  </div>
)
}

为什么?

javascript reactjs jsx
1个回答
1
投票

您没有将正确的参数传递给函数。你应该将props.shipping_lines传递给方法

export const LabelTop = props => {

    const getShippingMethod = (shipping_lines) => {
      const metaObj = shipping_lines.find(meta => meta.method_title !== "")
      return metaObj.method_title
    }

    return (
      <div>
        <div>
          <img src={LogoIcon} alt="Logo"/>
          <div>{props.orderNumber}</div>
        </div>
        <div>
          <div><span>Method:</span> {getShippingMethod(props.shipping_lines)}</div>
          <div><span>Customer:</span> {props.customerName}</div>
        </div>
      </div>
    )

}

但是,最好在Functional component之外编写方法,否则将在LabelTop组件的每个渲染上创建一个新的函数实例

编辑:组件可能没有以正确的格式获得道具。正如评论中所提到的,正在呈现组件的多个实例,并且所有实例都没有将prop作为数组获取,因此它会产生错误。

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