【问题标题】:How to get id from json with axios get request如何使用 axios get 请求从 json 中获取 id
【发布时间】:2022-01-05 03:34:53
【问题描述】:

我正在尝试从 json 文档中获取 idrestaurant 用作标识符,该文档在数据库中的 json 对象上具有此类信息。东西在 PostgreSQL 上

这是一个学校项目的反应网站。我尝试在控制台日志上打印 response.data,但没有显示任何内容。

[{"idrestaurant":2,
"name":"Pizzeria Amigo",
"address":"Uusikatu 16",
"opening":"08:00",
"closing":"12:00",
"img":"testi.com/kuva.jpg",
"type":"fastfood",
"pricelvl":"3",
"owneruserid":1},
{"idrestaurant":3,
"name":"Burgers",
"address":"Katu 10",
"opening":"08:00",
"closing":"18:00",
"img":"testi.com/kuva.png",
"type":"fastfood",
"pricelvl":"1",
"owneruserid":1}]

我想使用 id 作为 idrestaurant 作为在 Restaurant.js 打印餐厅元素列表的唯一键。这是我一直在尝试做的事情。

App.js

import React, { useEffect, useState } from 'react'
import './App.css'
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
import NavBar from './components/navBar'
import Restaurants from './components/Restaurants'
import searchRestaurant from './components/Search'
import Restaurant from './components/Restaurant'
import axios from 'axios'

const App = () => {
  const [restaurants, setRestaurants] = useState([])

  useEffect(() => {
    axios.get('http://MadeUpURL-app.herokuapp.com/restaurants')
      .then((response) => {
        setRestaurants(response.data)
      });
  }, []);
  return (
    <Router>
      <div>
        <NavBar />
        <Routes>
          <Route path='/restaurants' element={<Restaurants restaurants={restaurants} />} >
            <Route path="/restaurants/idrestaurant" element={<Restaurant restaurants={restaurants} />} />
          </Route>
          {/* <Route path='/Search' element={<Search />} /> */}
        </Routes>
      </div>
    </Router>
  );

}

export default App

Restaurants.js

import React from 'react'
import styles from './restaurants.module.css'
import Restaurant from './Restaurant'
import { Link } from 'react-router-dom'

const Restaurants = (props) => {
    return (
        <div className={styles.container}>
            <div className={styles.restaurantList}>
                {props.restaurants.map(restaurant => <Link to={restaurant.idrestaurant}>
                    <Restaurant key={restaurant.idrestaurant} />
                </Link>
                )}
            </div>
        </div>
    )
}

export default Restaurants

Restaurant.js

import React from 'react'
import styles from './restaurant.module.css'

export default function Restaurant(props) {
    return (
        <div className={styles.shop}>
            <div>
                <div><img src={props.img} className={styles.imageSize} /></div>
                <div>
                    <div className={styles.title}>{props.name}</div>
                    <div className={styles.type}>{props.type}</div>
                    <div className={styles.prange}>{props.pricelvl}</div>
                </div>
            </div>
        </div>
    )
}

【问题讨论】:

    标签: reactjs json axios react-router


    【解决方案1】:

    最好在Restaurants 组件内调用api。因为setRestaurants 需要时间来更新state,同时Restaurants 组件已经被渲染,所以&lt;Restaurants restaurants={restaurants} /&gt; 中的餐厅将是空的

    工作演示

    这是 App.js 的代码

    import React, { useEffect, useState } from "react";
    import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
    import Restaurants from "./components/Restaurants";
    import Restaurant from "./components/Restaurant";
        
    const App = () => {
      return (
        <Router>
          <div>
            <Routes>
              <Route path="/" element={<Restaurants />} />
              <Route path="/restaurants" element={<Restaurants />}>
                <Route path="/restaurants/idrestaurant" element={<Restaurant />} />
              </Route>
              {/* <Route path='/Search' element={<Search />} /> */}
            </Routes>
          </div>
        </Router>
      );
    };
    
    export default App;
    

    这里是 Restaurants.js 的代码

    import React, { useEffect, useState } from "react";
    import Restaurant from "./Restaurant";
    import { Link } from "react-router-dom";
    import axios from "axios";
    
    const Restaurants = (props) => {
      const [restaurants, setRestaurants] = useState([]);
    
      const jsonFakeData = [
        {
          idrestaurant: 2,
          name: "Pizzeria Amigo",
          address: "Uusikatu 16",
          opening: "08:00",
          closing: "12:00",
          img: "testi.com/kuva.jpg",
          type: "fastfood",
          pricelvl: "3",
          owneruserid: 1
        },
        {
          idrestaurant: 3,
          name: "Burgers",
          address: "Katu 10",
          opening: "08:00",
          closing: "18:00",
          img: "testi.com/kuva.png",
          type: "fastfood",
          pricelvl: "1",
          owneruserid: 1
        }
      ];
    
      useEffect(() => {
        axios.get("https://jsonplaceholder.typicode.com/users").then((response) => {
          console.log(response.data);
          //setRestaurants(response.data);
          setRestaurants(jsonFakeData);
        });
      }, []);
    
      return (
        <div>
          <div>
            {restaurants && restaurants.length > 0
              ? restaurants.map((restaurant) => (
                  <Link key={restaurant.idrestaurant} to={restaurant.idrestaurant}>
                    <Restaurant
                      restaurant={restaurant}
                      key={restaurant.idrestaurant}
                    />
                  </Link>
                ))
              : ""}
          </div>
        </div>
      );
    };
    
    export default Restaurants;
    

    这里是 Restaurant.js 的代码

    import React from "react";
    
    export default function Restaurant(props) {
      console.log(props, "prps");
      return (
        <div>
          <div>
            <div>
              <img src={props.restaurant.img} alt="img" />
            </div>
            <div>
              <div>{props.restaurant.name}</div>
              <div>{props.restaurant.type}</div>
              <div>{props.restaurant.pricelvl}</div>
            </div>
          </div>
        </div>
      );
    }
    

    【讨论】:

    • 答案有效。看到图片和文字。必须重新设计导航栏链接,但这不会那么痛苦。
    • 目前级别太低。会记得。
    猜你喜欢
    • 2019-07-27
    • 2021-05-03
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多