警告:收到 `children` 属性的 NaN。如果这是预期的,请将该值转换为字符串。反应问题

Warning: Received NaN for the `children` attribute. If this is expected, cast the value to a string. REACT problem

我是 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>

我得到的结果在这里:

我在控制台中得到它,但在我的屏幕上没有

你的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>