【发布时间】:2020-04-13 04:10:33
【问题描述】:
我正在尝试呈现一个表格,其中每一行 (1,2,3) 都有可扩展的行 (a,b,c)。 row 将从 API/rows 获取数据,expandable 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)。然后(exrows => {return exrows})},我得到了错误:对象作为react child(found:[object promise])无效,如果您打算渲染一组孩子,请改用数组。 循环行时我应该怎么做才能获得可扩展的行数据?提前致谢。
【问题讨论】:
-
改为使用函数
async和return await fetch(//...。 -
.then(results=>{return results.json();})有一个不必要的return而.then(expandData=>{...})缺少一个return -
你不能在这样的 React 渲染组件中间使用 Promise,
{this.getExpandableRow(row.id).then(exrows=>{return exrows})}
标签: javascript api object promise fetch