【发布时间】:2020-02-07 20:42:13
【问题描述】:
我不能对对象数组使用数组方法。 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;
【问题讨论】:
-
哪些方法不起作用?什么是错误
-
您完全忽略了设置
props的位置。除了console.log,我也没有看到任何使用shellsArray的代码。 -
"控制台的原型是array(0)" 这意味着原型是
Array构造函数,所以你应该可以调用数组方法。如果你这样做会怎样? -
我正在尝试使用 foreach(),但是当我使用这个 React 日志 TypeError: Cannot read property 'forEach' of undefined
-
你怎么称呼它?可以出示一下代码吗?
标签: javascript arrays reactjs javascript-objects react-hooks