我尝试在通过 axios 请求获取项目名称后显示它(这里的项目是一种成分)。我不明白我需要做什么才能使用“返回”项目名称。
Axios 毫无问题地返回了项目的名称,所以我尝试用 return <p>{response.data.name}</p>
来显示它但什么也没有显示。
我刚收到这条消息:“预期在箭头函数中返回一个值”
ListIng 被调用 (props.recipe.ing_list = ["whateverid", "whateverid"]) :
<td><ListIng list={props.recipe.ing_list} /></td>
我试着用这个来显示项目的名称:
const ListIng = props => (
props.list.map((item) => {
axios.get('http://localhost:4000/ingredient/' + item)
.then(response => {
return <p>{response.data.name}</p>
})
.catch(function (error) {
console.log(error)
})
})
)
这是我的第一篇文章,所以如果有任何我可以改进的地方,请不要犹豫告诉我 ;-)
最佳答案
您正在从 .then
回调函数返回值。返回值将传递给嵌套 .then
(如果有),但不会用作功能组件的返回值。
当你使用异步调用时,你应该使用状态,让 React 知道数据已经准备好,应该重新渲染组件。您可以使用 React Hooks 来实现这一点,如下所示(未测试,用作提示)
const ListIng = props => {
const [data, setData] = useState([]); // Initial data will be empty array
props.list.map((item) => {
axios.get('http://localhost:4000/ingredient/' + item)
.then(response => {
setData(e => ([...e, response.data.name])); // On each response - populate array with new data
})
.catch(function (error) {
console.log(error)
})
})
// Display resulting array as data comes
return <div>{data.map(d => ({<p>{d}</p>}))}</div>
}
关于javascript - axios请求后如何显示item名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57192660/