我正在尝试映射对象数组[{ingredient: '', quantity: ''}]并通过解构从中获取属性,这是代码 <ul> {this.state.ingredients.map(({ ingredient, quantity }, k) => { return ( <div key={k}> <li key={k}>{ingredient} - {quantity}</li><br /> </div> ) })} </ul>成分和不确定数量的回报甚至认为他们在状态值,但也有一些东西,有许多<li>在<ul>作为对象数组的lenght。那么这怎么可能呢?有什么办法可以解决吗?这是控制台日志记录:这是记录 state.ingredients 的图像这就是我从服务器获取成分的方式 axios.get(`/api/recipe/${params.id}/${params.name}`) .then(res => res.data) .then(data=>{ var jdata = JSON.parse(data.recipe) this.setState({ ingredients: jdata.ingredients, ... other properties }) console.log(jdata.ingredients) })
1 回答

心有法竹
TA贡献1866条经验 获得超5个赞
从输出中console.log(JSON.stringify(jdata.ingredients)),您的数组是数组数组,将数组数组转换为单个数组。
this.setState({
...
ingredients: [].concat.apply([], jdata.ingredients),
...
})
const arrays = [[{"ingredient":"sdasd","quantity":"asdas"}],[{"ingredient":"asdasd","quantity":"dsd"}]]
const merged = [].concat.apply([], arrays);
console.log(merged)
添加回答
举报
0/150
提交
取消