【问题标题】:Render axios response in Reactjs在 Reactjs 中渲染 axios 响应
【发布时间】:2022-01-26 18:46:58
【问题描述】:

我正在尝试在 reactjs 中呈现来自 Axios 的响应。响应是来自 MySQL 数据库的数据。请在下面查看我的代码并收到错误消息Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead. 我将不胜感激。谢谢。

const Products = () => {

  const fd =  () => {
    return Axios.get("http://localhost:5000/popular-products")
           .then(response => response.data)
  }

  return (
    <Container>
      {fd().then((data) => {
        data.map((item)=>(
          <h1>{item.prod_name}</h1>
        ))
      })}

    </Container>
  );
};

export default Products;

【问题讨论】:

  • 你正试图在 JSX 中解决承诺。在该函数 (fd) 中执行所有操作并获取最终数据。使用 useState 并使用最终数据设置状态,然后映射列表并返回 JSX。
  • 我试过useState,但是axios响应加载了多次
  • “多次加载”是什么意思?
  • @MattU 是的,它回答了我的问题。感谢您的帮助。

标签: reactjs axios


【解决方案1】:

在 JSX 之外解决 Promise 的最佳实践。如果你喜欢,你可以使用下面的方法。

const [items, setItems] = useState([]);

const fetch = () => {
    axios
      .get("http://localhost:5000/popular-products")
      .then((response) => setItems(response.data));
};

// component did mount
useEffect(() => {
   fetch();
}, []);

return (
  <div className="App">
      {items.length > 0 && items.map((item) => <p key={item.id}>{item.prod_name}</p>)}
  </div>
);

在这里,我使用组件确实 mount 来在组件安装时获取数据。

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 2018-03-24
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2020-03-25
    相关资源
    最近更新 更多