You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React-Query请求数据可打印却无法用map渲染,求技术解决

问题:React Query获取数据后map渲染无内容,但直接访问数组元素正常

控制台能打印出包含25个对象的数组,但使用data.map渲染页面时没有内容,直接取data[0].title却能正常显示。以下是相关代码:

import { useQuery } from "@tanstack/react-query";
import axios from "axios";
import "./App.css";

function App() {

  const fetchData = async () =>{
    const { data } = await axios.get("https://api.jikan.moe/v4/anime");
    const response = data.data;
    return response
  }

  const { isLoading,data,isError } = useQuery(
    ["posts"],
    fetchData,
      {
        retry: false,
        refreshInterval: 0,
        staleTime: 0
      }
  );
  if (isLoading) return <h1>...Loading</h1>;
  if (isError) return <h1>Fail</h1>;
    
  console.log(data)

  return (
    <div className="App">
      {data.map((datas)=>{
        <div>
          {datas.title}
        </div>
      })}
    </div>
  );
}

export default App;

解决方法

问题出在map的箭头函数上:你用了带大括号的箭头函数,但没有返回JSX元素。箭头函数如果用大括号包裹代码块,必须显式写return才能返回值;如果省略大括号,会自动返回表达式结果。

修正方式1:添加return

{data.map((datas)=>{
  return <div>
    {datas.title}
  </div>
})}

修正方式2:用圆括号包裹JSX(省略大括号,自动返回)

{data.map((datas)=>(
  <div key={datas.mal_id}> {/* React列表渲染必须添加唯一key属性,避免控制台警告 */}
    {datas.title}
  </div>
))}

另外补充:React列表渲染要求每个子元素拥有唯一的key属性,这里可以用每个动漫对象的mal_id作为key值,符合React的性能优化要求。


内容的提问来源于stack exchange,提问作者Josh Lee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:55:42