javascript - axios请求后如何显示项目名称
问题描述
在通过 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
如果有),但不会用作功能组件的返回值。
当你使用异步调用时,你应该使用 state 来让 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>
}
推荐阅读
- reactjs - 反应高图表不显示情节线
- javascript - 如何从内部图像onLoad返回变量
- c# - c#:通过电子邮件批准/拒绝:不是按钮:最少点击
- jquery - 卡在带有复选框的jquery中
- c# - MailKit.Net.Imap.ImapProtocolException:“IMAP 服务器问候语中的语法错误。意外的令牌:[atom:OK]”
- java - java - 如何随机生成0到3之间的整数而不使它们在Java中连续?
- bash - 从 Jenkins 的 .property 文件中读取数据并使用 Shell 脚本进行解析
- python - Python:尽管变量被定义为整数,为什么变量被视为“NoneType”?
- javascript - JQuery UI 对话框:TypeError: a(...).parents(...).andSelf is not a function
- javascript - 如何使用 React js 在下拉列表中显示数组值?