【问题标题】:Warning: Received NaN for the `children` attribute. If this is expected, cast the value to a string. REACT problem警告:收到的 `children` 属性的 NaN。如果这是预期的,请将值转换为字符串。反应问题
【发布时间】:2021-12-16 22:54:30
【问题描述】:

我是 react 新手,我正在尝试向我自己的 API 发出 GET 请求,然后在屏幕上呈现结果。当我这样做时,我console.log 我的结果也是如此,并且在控制台中我得到了正确的结果,但我不能把它放在我的屏幕上。我为此使用了useState

我的代码:

const url = "http://localhost:2000/appShop";
const [shop, showShop] = useState("");

const getShop = () => {
    Axios.get(url).then((response) => {
      console.log(response);
      showShop(response.data.name + response.data.address + response.data.city);
    });
  };


<Box
            sx={{
              "& > :not(style)": { m: 1, width: "25ch" },
            }}

          >
            <span>{shop}</span>
            <Button onClick={getShop}>List all Shops</Button>
            <Button onClick={() => showShopCard(false)}>Close</Button>
</Box>

我得到的结果在这里:

我在控制台中得到它,但不是在我的屏幕上

【问题讨论】:

  • 你应该归还你的
  • @NiceBooks 你能说得更具体点吗?
  • response.data 是一个数组,如您的日志所示,它没有nameaddress 等。您得到NaN,因为您有undefined + undefined + undefined
  • @tromgy 但那我该怎么办呢?认为我的路径“response.data”是正确的
  • 已解决@NiceBooks,谢谢。是的,我确实退回了盒子,我只是没有在这里复制它

标签: reactjs api axios request frontend


【解决方案1】:

您的 response.data 是一个数组。 您需要遍历数组并将结果保存在状态中,此外您需要为数组中的每个元素创建一个跨度项:

const url = "http://localhost:2000/appShop";
const [shop, showShop] = useState("");
const [shopList, setShopList] = useState([]);

const getShop = () => {
    Axios.get(url).then((response) => {
      console.log(response);
      const shopListItems = [];
      response.data.forEach(resItem => {
        shopListItems.push(resItem.name + resItem.address + resItem.city)
      })
      setShopList(shopListItems)
    });
  };


<Box
            sx={{
              "& > :not(style)": { m: 1, width: "25ch" },
            }}

          >
            {shopList.map((sl, index) => (<span key={index}>{sl}</span>))}
            <Button onClick={getShop}>List all Shops</Button>
            <Button onClick={() => showShopCard(false)}>Close</Button>
</Box>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    相关资源
    最近更新 更多