[英]nested javascript fetches return [object promise] value
我正在尝试呈现一个表格,其中每一行 (1,2,3) 都有可扩展的行 (a,b,c)。 row 将从 API/rows 获取数据,可扩展行将从 API/rowId?expandableRows 获取数据。 像这样呈现时,可扩展行将跟随它的行:
row col1 col2 col3
1 x x x
a x x x
b x x x
2 x x x
a x x x
3 x x x
a x x x
这是我的代码
class Table extends Component {
constructor(){
super();
this.state={ rowList: [] }
}
componentDidMount() {
fetch(API/rows)
.then(results=>{return results.json()})
.then(rows =>{
let rowList= rows.map(row=> {
return (
<react.Fragment>
<tr><td>{row.info}</td></tr>
{this.getExpandableRow(row.id).then(exrows=>{return exrows})}
</react.Fragment>
)
})
this.setState(rowList: rowList);
})
}
getExpandableRow(id) {
return fetch(api/rowid?expandableRows)
.then(results=>{return results.json();})
.then(expandData=>{
data.map(dat=>{
return (
<tr><td>expandrow.info</td></tr>
)
})
console.log(expandData)
})
}
render(){
return (<Table>{this.state.rowList}</Table>)
}
}
现在的问题是我可以在 console.log 中看到扩展数据,但是在行循环中调用 getExpandableRows 函数时,无论使用 {this.getExpandableRow(row.id)} 还是 {this.getExpandableRow(row.id).then(exrows =>{return exrows})},我收到错误:对象无效,因为 react child(found:[object promise]),如果您打算渲染一组子项,请改用数组。 循环行时我应该怎么做才能获得可扩展的行数据? 提前致谢。
我还没有测试过这个,但我认为你可以逃脱这个:
componentDidMount() {
fetch(API/rows)
.then(results=>{return results.json()})
.then(async rows =>{
// this will be an array of promises
let rowExpPromiseList = rows.map(row=> {
return this.getExpandableRow(row.id);
});
// I believe this will be an array of components at this point
const rowExpList = await Promise.all(rowExpPromiseList);
const rowList = rows.map((row, index) => (
<react.Fragment>
<tr><td>{row.info}</td></tr>
{rowExpList[index]}
</react.Fragment>
));
this.setState(rowList: rowList);
})
}
在尝试渲染需要它们的反应组件之前,您会获得可扩展的行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.