简体   繁体   中英

How to print JSON data from axios? -react-

The problem is I don't know how to print Json data with React.

JSON :

{
    "themes": [
        {
            "id": 1,
            "name": "nature",
            "trips": [
                {
                    "id": 1,
                    "location": "Jeju",
                    "price_discounted": 11200
                },
                {
                    "id": 2,
                    "location": "Seoul",
                    "price_discounted": 11200
                },
            ]
        }
    ]
}

and I tried

function Card() {
  const [users, setUsers] = useState([]);
  const fetchUsers = async () => {
    const response = await axios.get(process.env.REACT_APP_PRODUCT_URL);
    setUsers(response.data.themes);
    console.log(response.data);
  };

  useEffect(() => {
    fetchUsers();
  }, []);
  return (
    <div>
      {users.map((user) => (
        <li>{user.name.trips}</li>
      ))}
    </div>
  );
}

but I can`t get "trips"'s data.. Help me!

I can only get "themes"'s "id" and "name"

You wrote user.name.trips which is not valid. Here, trips is not a child of name . To get a trip, you need to write:

user.trips[0].id or user.trips[1].price_discounted or ...

The index in bracket is needed because trips is an array here. Also, every trip is an object, so you need to specify which "key/value" pair you want to output.
The General code is:
user.trips[(index of trip)].(id or location orprice_discounted)

In your json you are using variable wrongly. name is a string. trips is object. both are different props.

  {users.map((user) => {
    return user.trips(trip=>{
          return <li>{trip.location}</li>
          }

   }
 )}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM