【问题标题】:React.js cant itterate through an array with .map from useStateReact.js 无法使用来自 useState 的 .map 遍历数组
【发布时间】: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 error console.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


【解决方案1】:

首先,控制组件总是更容易。

const [foodText, setFoodText] = useState('');
const [unitBox, setUnitBox] = useState('');
const [foodAmount, setFoodAmount] = useState(0);

<input 
 id='foodText' 
 value={foodText} 
 onChange={(e) =>setFoodText(e.target.value)} 
 type="text" 
/>

<select id='unitBox' value={unitBox} onChange={(e) => setUnitBox(e.target.value)}>
    {UnitsArray.map(unit=>(
        <option>{unit}</option>
        ))}
</select>
<input 
 id='FoodAmount' 
 type='number' 
 value={foodAmount} 
 onChange={(e) =>setFoodAmount(e.target.value)} 
/>
<button onClick={props.click} type="submit">Add</button>

当您的组件受到控制时,您无需访问 DOM 即可获取值。

const Foodie = () =>{
setFoodList([...FoodList,{
        'Item':foodText,
        'Unit':unitBox,
        'Quantity':foodAmount
       }])

console.log('changed')
}

最后:(只是编辑你想要做的任何事情)

useEffect(()=>{
 props.aId.map(food=> console.log(food))
},[props.aId]);

useEffect(()=>{
 props.aId.map(food=> console.log(food.Item))
},[props.aId]);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-14
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多