[英]How to handle map product not found in react dropdown
我想在下面以粗體突出顯示的代碼中處理不匹配的結果。 目前,它將使用 GraphAPI 從 AzureAD 獲取信息。 如果產品匹配,則它設置值。 目前,如果產品不存在於 const Sale 中,則會拋出錯誤。 如果價值產品不匹配,有什么方法可以將默認值設置為空或 null。
export const PO ={
STYLE: "Wired",
STYLE2: "Wireless"
}
export const Sale = [
{
product: "headset",
pu: PO.STYLE,
brand: "jbl"
},
{
product: "headset",
pu: PO.STYLE,
brand: "sony"
},
{
product: "headset",
pu: PO.STYLE2,
brand: "beats"
}
];
const { control, watch, setValue } = useForm<IFormValues>({
defaultValues: {
...user,
product:Sale.find((d) => d.product === user.sale).product, //Currently it throwing exception if it not match.
},
});
//Get Form Values
const formValues = watch()
const {product, brand } = Sale.find((d) => d.product === formValues.product);
const productOptions = Object.values(PO).map((product) => ({key: product, text: product}));
return (
<Label>Product</Label>
<Controller as="input" name="product" type="hidden" control= {control} />
<Dropdown
options = {productOptions}
selectedKey = {formValues.product}
onchange = {(_, option: IDropdownOption) => {
setValue("product", option.key);
})
/>
}
export const PO ={
STYLE: "Wired",
STYLE2: "Wireless",
DEFAULT: null
}
export const Sale = [
{
product: "headset",
pu: PO.STYLE,
brand: "jbl"
},
{
product: "headset",
pu: PO.STYLE,
brand: "sony"
},
{
product: "headset",
pu: PO.STYLE2,
brand: "beats"
},
{
product: null,
pu: PO.DEFAULT,
brand: null
},
];
export interface ProductInfo{
product: Product;
}
const { control, watch, setValue } = useForm<IFormValues>({
defaultValues: {
...user,
product:GetProduct(product)
},
});
//GetProduct
function GetProduct(product: Product)
{
let productInfo = Sale.find((d) => d.product === user.sale);
if(!productInfo)
{
return PO.DEFAULT;
}
return productInfo.po;
}
//Get Form Values
const formValues = watch()
const {product, brand } = Sale.find((d) => d.product === formValues.product);
const productOptions = Object.values(PO).map((product) => ({key: product, text: product}));
return (
<Label>Product</Label>
<Controller as="input" name="product" type="hidden" control= {control} />
<Dropdown
options = {productOptions}
selectedKey = {formValues.product}
onchange = {(_, option: IDropdownOption) => {
setValue("product", option.key);
})
/>
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.