【发布时间】: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