首页 > 解决方案 > 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)
            })
        })
    )

这是我的第一篇文章,所以如果有什么我可以改进的,请不要犹豫告诉我;-)

标签: javascriptnode.jsreactjsaxios

解决方案


您正在从.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>
}

推荐阅读