[英]Error: Objects are not valid as a React child (found: [object Promise]) in reactjs
I'm learning reactjs.我正在学习 reactjs。 I want to get result from fuction findTenloaidv(id) when load list bpdvList but error
我想在加载列表 bpdvList 时从函数 findTenloaidv(id) 中获取结果但错误
async componentDidMount(){
this.setState({isLoading: true});
const bangphi = await (await fetch(`/gvnhanh/bangphidv/`)).json();
this.setState({
bpdvs: bangphi,
isLoading: false,
})
}
async findTenloaidv(id){
const loaidv = await (await fetch(`/gvnhanh/loaidv/${id}`)).json();
return loaidv.tenloai
}
render(){
const {bpdvs, isLoading} = this.state;
const bpdvList = bpdvs.map(bpdv =>{
return <tr key={bpdv.idbpdv}>
<td className="text-center">{bpdv.iddv}</td>
<td className="text-center">{this.findTenloaidv(bpdv.idloaidv)}</td>
<td className="text-center">{bpdv.tendv}</td>
<td className="text-center">{bpdv.mota}</td>
<td className="text-center">{this.currencyFormat(bpdv.gia)}</td>
<td className="text-center">{bpdv.donvitinh}</td>
</tr>
});
}
There are a couple errors here.这里有几个错误。
async componentDidMount(){
this.setState({isLoading: true});
const bangphi = await (await fetch(`/gvnhanh/bangphidv/`)).json(); // Here
const bangphi = await fetch('Your endpoint') //await your fetch data
const data = await bangphi.json() // Then convert to json
this.setState({
bpdvs: data.bangphi, // changed here
isLoading: false,
})
}
// Change this to match
async findTenloaidv(id){
const loaidv = await (await fetch(`/gvnhanh/loaidv/${id}`)).json();
return loaidv.tenloai
}
The problem is here问题就在这里
<td className="text-center">{this.findTenloaidv(bpdv.idloaidv)}</td>
findTenloaidv
method returns a promise
as it is async
which is type of object ([object Promise])
. findTenloaidv
方法返回一个promise
因为它是async
,它是对象([object Promise])
。 That's why react throws this error Objects are not valid as a React child
.这就是为什么 react 会抛出这个错误
Objects are not valid as a React child
。
You need to map the currency format while you're fetching data.您需要在获取数据时映射货币格式。 Try like this
像这样尝试
async componentDidMount(){
this.setState({isLoading: true});
const bangphi = await (await fetch(`/gvnhanh/bangphidv/`)).json(); // Here
const bangphi = await fetch('Your endpoint') //await your fetch data
const data = await bangphi.json() // Then convert to json
const bpdvs = data.bangphi.map(async bpdv => {
const loaidv = await this.findTenloaidv(bpdv.idloaidv)
return {
...bpdv,
idloaidv: loaidv.tenloai
}
})
this.setState({
bpdvs,
isLoading: false,
})
}
...
<td className="text-center">{bpdv.iddv}</td>
<td className="text-center">{bpdv.idloaidv}</td>
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.