gpt4 book ai didi

javascript - 无法对对象数组使用数组方法

转载 作者:行者123 更新时间:2023-12-02 22:47:40 24 4
gpt4 key购买 nike

我无法对对象数组使用数组方法。 shellsArray 在控制台中注销 (6) [{…}, {…}, {…}, {…}, {…}, {…}],但我无法使用数组其上的方法。控制台的原型(prototype)是 array(0)

    import React, { useState } from 'react'

const RecipeForm = (props) => {
const [baseLayer, setBaseLayer] = useState('');
const [condiment, setCondiment] = useState('');
const [mixing, setMixing] = useState('');
const [seasoning, setSeasoning] = useState('');
const [shell, setShell] = useState('');
**let tacos = props.tacos;
let shellsArray = tacos.shells;** // Shows an array that I cannot use array methods on
console.log(shellsArray);

const submitHandler = (e) => {
e.preventDefault();
props.saveCombination(baseLayer, condiment, mixing, seasoning, shell);
setBaseLayer('');
setCondiment('');
setMixing('');
setSeasoning('');
setShell('');
}
return (
<form onSubmit={submitHandler} >
<select className="base-layer" name="baseLayer" value={baseLayer} onChange={(e) => setBaseLayer(e.target.value)} required >
<option>SELECT BASE LAYER</option>
<option>Mexican</option>
<option>Asian</option>
</select>
<select className="condiment" name="condiment" value={condiment} onChange={(e) => setCondiment(e.target.value)} required >
<option>SELECT CONDIMENT</option>
<option>Tomato</option>
<option>Lettuce</option>
</select>
<select className="mixing" name="mixing" value={mixing} onChange={(e) => setMixing(e.target.value)} required >
<option>SELECT MIXING</option>
<option>Tomato</option>
<option>Lettuce</option>
</select>
<select className="seasoning" name="seasoning" value={seasoning} onChange={(e) => setSeasoning(e.target.value)} required >
<option>SELECT SEASONING</option>
<option>Tomato</option>
<option>Lettuce</option>
</select>
<select className="shell" name="shell" value={shell} onChange={(e) => setShell(e.target.value)} required >
<option>SELECT SHELL</option>
<option>Tomato</option>
<option>Lettuce</option>
</select>
<input type="submit" className="submit" />
</form>
);
}

export default RecipeForm;

最佳答案

如果您的 shells 数组是一个 prop,那么您似乎在定义该 prop 之前尝试使用它。这是一种常见的情况,通常的方法是通过首先测试数组是否已定义来防止错误。最简单的方法是使用快捷条件条件:

Array.isArray(shells) && shells.map(shell=>{}) //or whatever

关于javascript - 无法对对象数组使用数组方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58322299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com