簡體   English   中英

根據 React 中的動態選擇值獲取 Id

[英]Get Id Based on Dynamic Selected Values in React

我有幾個具有動態值的productOptionTypes 我的問題是如何將它與它的variants匹配。 我想根據它獲取variant id

請在此處檢查代碼和框單擊此處

{productOptionTypes.map((item, index) => (
  <>
    <span className="title">{item.optionName}</span>
    <Select
      placeholder={`${item?.optionValues?.length} ${item.optionName}s`}
      options={item.optionValues.map((option) => {
        return { label: option, value: option };
      })}
      isSearchable={false}
      onChange={(value) => handleSelectVariant(value, index)}
    />
  </>
))}

當我正確理解它時,您希望保護每個選定的值,然后將結果與您的變體和 select 與基於它的所有選擇框匹配的項目的變量 ID 進行比較?

index.js

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import Select from "react-select";
import "./styles.css";
import { productOptionTypes } from "./productOptionTypes";
import { variants } from "./variants";

function App() {
  const [variantType, setSelectedVariant] = useState({});
  const [result, setResult] = useState(null);

  const mapIndexKey = {
    0: "option1Value",
    1: "option2Value",
    2: "option3Value",
    3: "option4Value"
  };

  useEffect(() => {
    setResult(
      variants.filter(
        (el) =>
          el.option1Value == variantType.option1Value &&
          el.option2Value == variantType.option2Value &&
          el.option3Value == variantType.option3Value &&
          el.option4Value == variantType.option4Value
      )
    );
  }, [variantType]);

  useEffect(() => {
    console.log(result);
  }, [result]);

  const handleSelectVariant = (value, index) => {
    setSelectedVariant({ ...variantType, [mapIndexKey[index]]: value.value });
    console.log(variantType, value, index);
  };

  return (
    <div className="App">
      <form>
        {productOptionTypes.map((item, index) => (
          <>
            <span className="title">{item.optionName}</span>
            <Select
              placeholder={`${item?.optionValues?.length} ${item.optionName}s`}
              options={item.optionValues.map((option) => {
                return { label: option, value: option };
              })}
              isSearchable={false}
              onChange={(value) => handleSelectVariant(value, index)}
            />
          </>
        ))}
      </form>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

變種.js

export const variants = [
  {
    id: "60451fd290aeb720d96d8459",
    name: "Women's Bellarina Half Toe Grip Yoga Pilates Barre Socks",
    wholesalePrice: "8.0",
    sku: "s01524blk",
    option1Type: "Color",
    option1Value: "Black",
    option2Type: "Size",
    option2Value: "XS",
    option3Type: "Toe Type",
    option3Value: "Half Toe",
    option4Value: "Bellarina",
    retailPrice: "16.0",
    __typename: "Variant"
  },
  {
    id: "60451fd790aeb720d96d8463",
    name: "Women's Bellarina Half Toe Grip Yoga Pilates Barre Socks",
    wholesalePrice: "8.0",
    sku: "s01525blk",
    option1Type: "Color",
    option1Value: "Black",
    option2Type: "Size",
    option2Value: "S",
    option3Type: "Toe Type",
    option3Value: "Half Toe",
    retailPrice: "16.0",
    __typename: "Variant"
  }
}

基本上我所做的是將所有選定的值保存在 map 中,並且每次更改值時只需將其與所有變體進行比較,如果變體等於 select 它。 對於一個變體,我添加了第四個鍵“Bellarina”。

我希望這個解決方案可以解決您的問題。

當您想驗證解決方案時,只需 select 每個選擇框的第一個值並查看控制台。

我能想到的最好的是:

  1. 更新選項映射以返回選項名稱,用作variants數組對象的外鍵,即“顏色”、“大小”等。

     options={item.optionValues.map((option) => { return { label: option, value: option, name: item.optionName }; })}
  2. variantType state 更新為 object,並更新handleSelectVariant處理程序以通過外鍵“name”和選定的“value”存儲變體類型

    const [variantType, setSelectedVariant] = useState({}); const handleSelectVariant = (value, index) => { setSelectedVariant((state) => ({...state, [value.name]: value.value })); };
  3. 使用filterevery function 將選項類型和值減少為可以輕松映射到id屬性的變體的過濾結果。

     const matches = variants.filter((variant) => { return [ ["option1Value", "option1Type"], ["option2Value", "option2Type"], ["option3Value", "option3Type"], ["option4Value", "option4Type"], ["option5Value", "option5Type"], ["option6Value", "option6Type"], ["option7Value", "option7Type"], ["option8Value", "option8Type"], ["option9Value", "option9Type"], ["option10Value", "option10Type"] ].every(([key, valueKey]) => variantType[variant[valueKey]]? variant[key] === variantType[variant[valueKey]]: true ); }).map(({ id }) => id);

演示

編輯 get-id-based-on-dynamic-selected-values-in-react

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM