【发布时间】:2019-09-09 14:21:30
【问题描述】:
在我的项目中,我以简单的形式从用户那里收集输入,然后我想通过 useState 将该输入保存在对象设置数组中。我更新了状态,当我打印状态时我可以看到对象,但是如果我需要特定的数据,我就无法获得。
表单(收集用户输入):
<input id='foodText' type="text" />
<select id='unitBox'>
{UnitsArray.map(unit=>(
<option>{unit}</option>
))}
</select>
<input id='FoodAmount' type='number' />
<button onClick={props.click} type="submit">Add</button>
props.click 和 useState(这两个都在 app.js 主文件中)
const [FoodList, setFoodList] = useState([]);
const Foodie = () =>{
setFoodList([...FoodList,{'Item':document.getElementById('foodText').value,
'Unit':document.getElementById('unitBox').value,
'Quantity':parseInt(document.getElementById('FoodAmount').value)}])
console.log('changed')
}
最后,这是我使用 array.map() 遍历它的时候
useEffect(()=>{props.aId.map(food=>(console.log({food})))},[props.aId]);
useEffect(()=>{props.aId.map(food=>(console.log({food['Item']})))},[props.aId]);
//this will throw an exception error when I run it.
任何建议或想法将不胜感激。
【问题讨论】:
-
//this will throw an exception errorconsole.logprops.aId来检查它的值吗? -
我的错,我以为我添加了那个。这是一个解析错误:'Line 8: Parsing error: Unexpected token, expected ","'
-
你为什么用
document.getElementById('FoodAmount').value设置状态不能用state代替? -
Unexpected token表示你不尊重 JS 语法。使用 IDE 或任何工具来验证您的代码。Unexpected token表示您不尊重 JS 语法。使用 IDE 或任何工具来验证您的代码。如果我是你,我会尝试console.log({food['Item']})-->console.log(food['Item']),不确定你是否可以这样做,以及它会为密钥取什么值...... -
{food['Item']}不是构造对象的有效方法
标签: javascript reactjs react-hooks