【发布时间】:2022-06-27 07:36:51
【问题描述】:
我正在通过 Dot Net 6 和 React 开发一个简单的食品订购应用程序。
我有一张食物清单表,其中包含该特定食物的所有详细信息,包括提供该食物的餐厅。
在表格中,我想显示餐厅的名称,而不是来自食物数据的 ID。 list of foods
我的内在方法是使用这个函数
function getRestaurantById(id: number) {
let res = '';
axios.get('https://localhost:7005/api/Restaurant/' + id).then(response => {
res = response.data.name;
});
return res;
}
当控制台登录 axios 的 .then() 方法时,我得到了我想要的餐厅名称。但是,res 变量被保存为未定义。我该如何解决这个问题?我希望这个函数返回一个字符串值。
注意:我不能(或者可能但不知道如何)使用 useState 函数,因为我将在表数据中调用此函数。
{foods.map(food => (
<tr key={food.foodId}>
<td>{food.foodId}</td>
<td>{food.name}</td>
<td>{food.ingredients}</td>
<td>{food.price}</td>
<td>{food.cuisineType}</td>
<td>{getRestaurantById(food.restaurant)}</td>
<td><Button className='btn' onClick={() => {setFood(food); handleFormOpen()}}>Edit</Button></td>
<td><Button className='btn action' onClick={() => deleteFood(food.foodId.toString())}>Delete</Button></td>
</tr>
))}
【问题讨论】:
标签: reactjs