我的应用正在渲染此组件:
<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>
)
}
为什么?
答案 0 :(得分: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作为数组获取,因此会产生错误。