不能对对象数组使用数组方法



我不能在对象数组上使用数组方法。shellsArray 在控制台中注销(6) [{…}, {…}, {…}, {…}, {…}, {…}],但我无法在其上使用数组方法。控制台的原型显示数组(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数组是一个道具,看起来你在定义道具之前就试图使用它。这是一种常见的情况,通常的方法是通过首先测试数组是否已定义来防止错误。最简单的方法是使用快捷方式条件:

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

相关内容

  • 没有找到相关文章

最新更新