无法读取相关下拉列表中未定义错误的属性

发布于 2025-01-16 05:23:59 字数 2666 浏览 1 评论 0原文

我正在尝试制作依赖下拉列表。在第一个菜单中我选择汽车品牌。在第二个菜单中,我应该只看到所选品牌的型号。在函数 selectBrand 中,我尝试设置 selectedBrand 的新值,并将所选品牌的模型设置为模型数组,但在第二个 setAdData 中,我得到未捕获的类型错误:无法读取未定义的属性(读取“模型”)。我该如何解决这个问题?

const [adData, setAdData] = useState({
    selectedBrand: "",
    models: [],
    selectedModel: "",
    productionYear: "",
    countryOfOrigin: "",
    typeOfFuel: "",
    bodyType: "",
    amountOfDoors: "",
    typeOfGearbox: "",
    typeOfDrive: "",
    color: "",
    typeOfColor: "",
    description: "",
    vin: "",
    engineCapacity: "",
    mileage: "",
    horsePower: "",
    price: "",
    creator: "",
    image: "",
});

const selectBrand = (e) => {
    setAdData({...adData, selectedBrand: e.target.value});
    setAdData({...adData, models: data.cars.find(car => car.brand===e.target.value).models})
}

return (
    <Paper className={classes.paper}>
        <form autoComplete="off" noValidate className={`${classes.root} ${classes.form}`} onSubmit={handleSubmit}>
            
        <Typography variant="h6">Brand</Typography>
        <Select fullWidth value={adData.selectedBrand} onChange={selectBrand.bind(this)
        }>
            {data.cars.map((car, key) => {
                return <MenuItem key={key} value= {car}>{car.brand}</MenuItem>
            })}
        </Select>

        <Typography variant="h6">Model</Typography>
        <Select fullWidth value={adData.selectedModel} onChange={(e) => 
            setAdData({...adData, selectedModel: e.target.value})
        }>
            {
                adData.models.map((model, key) => {
                    return <MenuItem key={key} value={model}>{model}</MenuItem>
                })
            }
        </Select>

        <Button className={classes.buttonSubmit} variant="contained" color="primary" size="large" type="submit" fullWidth>Dodaj</Button>
        <Button variant="contained" color="secondary" size="large" onClick={clear} fullWidth>Anuluj</Button>
        </form>
    </Paper>
);

data.json 我有汽车和模型

{
"cars":[
   {
      "brand":"BMW",
      "models":[
         "Seria 1",
         "Seria 2",
         "Seria 3",
         "Seria 4",
         "Seria 5",
         "Seria 6",
         "Seria 7",
         "Seria 8"
      ]
   },
   {
      "brand":"Audi",
      "models":[
         "A1",
         "A2",
         "A3",
         "A4",
         "A5",
         "A6",
         "A7",
         "A8"
      ]
   }
],                                                                              
}

Im trying to make dependent dropdown list. In the first one menu i choose car brand. In 2nd menu I should see only models of selected brand. In a function selectBrand I am trying to set new value of selectedBrand and set models of selected brand to models arrays but in 2nd setAdData I get Uncaught TypeError: Cannot read properties of undefined (reading 'models'). How Can I fix that?

const [adData, setAdData] = useState({
    selectedBrand: "",
    models: [],
    selectedModel: "",
    productionYear: "",
    countryOfOrigin: "",
    typeOfFuel: "",
    bodyType: "",
    amountOfDoors: "",
    typeOfGearbox: "",
    typeOfDrive: "",
    color: "",
    typeOfColor: "",
    description: "",
    vin: "",
    engineCapacity: "",
    mileage: "",
    horsePower: "",
    price: "",
    creator: "",
    image: "",
});

const selectBrand = (e) => {
    setAdData({...adData, selectedBrand: e.target.value});
    setAdData({...adData, models: data.cars.find(car => car.brand===e.target.value).models})
}

return (
    <Paper className={classes.paper}>
        <form autoComplete="off" noValidate className={`${classes.root} ${classes.form}`} onSubmit={handleSubmit}>
            
        <Typography variant="h6">Brand</Typography>
        <Select fullWidth value={adData.selectedBrand} onChange={selectBrand.bind(this)
        }>
            {data.cars.map((car, key) => {
                return <MenuItem key={key} value= {car}>{car.brand}</MenuItem>
            })}
        </Select>

        <Typography variant="h6">Model</Typography>
        <Select fullWidth value={adData.selectedModel} onChange={(e) => 
            setAdData({...adData, selectedModel: e.target.value})
        }>
            {
                adData.models.map((model, key) => {
                    return <MenuItem key={key} value={model}>{model}</MenuItem>
                })
            }
        </Select>

        <Button className={classes.buttonSubmit} variant="contained" color="primary" size="large" type="submit" fullWidth>Dodaj</Button>
        <Button variant="contained" color="secondary" size="large" onClick={clear} fullWidth>Anuluj</Button>
        </form>
    </Paper>
);

data.json where I have cars and models

{
"cars":[
   {
      "brand":"BMW",
      "models":[
         "Seria 1",
         "Seria 2",
         "Seria 3",
         "Seria 4",
         "Seria 5",
         "Seria 6",
         "Seria 7",
         "Seria 8"
      ]
   },
   {
      "brand":"Audi",
      "models":[
         "A1",
         "A2",
         "A3",
         "A4",
         "A5",
         "A6",
         "A7",
         "A8"
      ]
   }
],                                                                              
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

酒几许 2025-01-23 05:23:59

这是因为,如果用户选择的汽车品牌在 data.cars 中不存在,并且 .find() 返回 undefined,那么您尝试读取 undefined.models ,这会给您一个错误

一种选择是您可以使用三元运算符来检查 find 是否返回数组,然后获取如下所示的模型(替换 <代码>宝马与e.target.value

data.cars.find(car => car.brand === "BMW") ? data.cars.find(car => car.brand === "BMW").models : []

概念工作例如

var data = {
  "cars": [{
      "brand": "BMW",
      "models": [
        "Seria 1",
        "Seria 2",
        "Seria 3",
        "Seria 4",
        "Seria 5",
        "Seria 6",
        "Seria 7",
        "Seria 8"
      ]
    },
    {
      "brand": "Audi",
      "models": [
        "A1",
        "A2",
        "A3",
        "A4",
        "A5",
        "A6",
        "A7",
        "A8"
      ]
    }
  ]
}

console.log(data.cars.find(car => car.brand === "sd") ? data.cars.find(car => car.brand === "sd").models : []);

console.log(data.cars.find(car => car.brand === "BMW") ? data.cars.find(car => car.brand === "BMW").models : []);
  

That's because in case the user selected car brand does not exist in data.cars, and .find() returns undefined, then you try to read .models of undefined which gives you an error

One option is you can have a ternary operator to check if find returns an array, then get the models like below (replace BMW with e.target.value )

data.cars.find(car => car.brand === "BMW") ? data.cars.find(car => car.brand === "BMW").models : []

Concept Working eg

var data = {
  "cars": [{
      "brand": "BMW",
      "models": [
        "Seria 1",
        "Seria 2",
        "Seria 3",
        "Seria 4",
        "Seria 5",
        "Seria 6",
        "Seria 7",
        "Seria 8"
      ]
    },
    {
      "brand": "Audi",
      "models": [
        "A1",
        "A2",
        "A3",
        "A4",
        "A5",
        "A6",
        "A7",
        "A8"
      ]
    }
  ]
}

console.log(data.cars.find(car => car.brand === "sd") ? data.cars.find(car => car.brand === "sd").models : []);

console.log(data.cars.find(car => car.brand === "BMW") ? data.cars.find(car => car.brand === "BMW").models : []);
  

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文