无法在对象数组上使用数组方法

时间:2019-10-10 11:52:34

标签: javascript arrays reactjs javascript-objects react-hooks

我不能在对象数组上使用数组方法。 shellsArray在控制台中注销(6) [{…}, {…}, {…}, {…}, {…}, {…}],但无法在其上使用数组方法。控制台的原型显示为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;

1 个答案:

答案 0 :(得分:1)

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

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