【问题标题】:Adding JSON data to React将 JSON 数据添加到 React
【发布时间】:2021-02-19 16:03:26
【问题描述】:

我已经能够从我使用 MongoDB 和 Express 构建的 API 中提取数据,但是在将嵌套数据渲染到我的 React 组件时遇到了问题。

例如,如果我输入 <p>{restaurant.cuisine}</p>,我可以检索 Burgers, American,但如果我尝试访问 {restaurant.status.delivery},我会收到一条错误消息:

无法读取未定义的属性“delivery”。

但是如果我{console.log(restaurant.status} 我可以看到对象吗?我尝试使用 Object.values 将对象转换为数组,但这也不起作用。

如果我尝试访问 {restaurant.images}{restaurant.geometry} 中的嵌套对象,也会发生同样的事情。

这是我的 React 钩子的副本:

import { useReducer, useEffect } from 'react';
import axios from 'axios';

const ACTIONS = {
  MAKE_REQUEST: 'make-request',
  GET_DATA: 'get-data',
  ERROR: 'error',
};

function reducer(state, action) {
  switch (action.type) {
    case ACTIONS.MAKE_REQUEST:
      return { loading: true, restaurant: [] };
    case ACTIONS.GET_DATA:
      return {
        ...state,
        loading: false,
        restaurant: action.payload.restaurant,
      };
    case ACTIONS.ERROR:
      return {
        ...state,
        loading: false,
        error: action.payload.error,
        restaurant: [],
      };
    default:
      return state;
  }
}

export default function useFetchSingleRestaurant({ id }) {
  const [state, dispatch] = useReducer(reducer, {
    restaurant: [],
    loading: true,
  });

  useEffect(() => {
    dispatch({ type: ACTIONS.MAKE_REQUEST });
    axios
      .get('http://localhost:4444/restaurants/' + id)
      .then((res) => {
        dispatch({
          type: ACTIONS.GET_DATA,
          payload: { restaurant: res.data.restaurant },
        });
      })
      .catch((e) => {
        dispatch({
          type: ACTIONS.ERROR,
          payload: { error: e },
        });
      });
  }, [id]);

  return state;
}

我在我的 SingleRestaurant 组件中访问它:

function SingleRestaurant({ match }) {
  const { restaurant } = useFetchSingleRestaurant({ id: match.params.id });

  return ( 
    <p>{restaurant.status.delivery}</p>
  ) 
}

这也是我的后端设置:

showRestaurant = async (req, res) => {
  const restaurant = await Restaurant.findById(req.params.id)
    .populate({ path: 'reviews', populate: { path: 'author' } })
    .populate('author');
  if (!restaurant) {
    req.flash('error', 'Restaurant not found.');
    return res.redirect('/restaurants');
  }
  res.send({ restaurant });
};

【问题讨论】:

    标签: json reactjs mongodb express


    【解决方案1】:

    在您的服务器请求返回 restaurant 之前,它将被设置为您设置的默认 []

    空数组没有status 的属性,因此出现错误。

    如果您将默认值更改为 null:

    const [state, dispatch] = useReducer(reducer, {
        restaurant: null,
        loading: true,
      });
    

    然后检查一个值:

    function SingleRestaurant({ match }) {
      const { restaurant } = useFetchSingleRestaurant({ id: match.params.id });
      if (!restaurant) return 'Loading'
    
      return ( 
        <p>{restaurant.status.delivery}</p>
      ) 
    }
    

    你也可以从你的钩子传回加载状态,然后检查它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-13
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 2014-11-11
      • 1970-01-01
      • 2016-10-25
      相关资源
      最近更新 更多