对象作为 React 子项无效(已找到:具有键 {_id, date, createdAt, updatedAt, __v} 的对象)

Objects are not valid as a React child (found: object with keys {_id, date, createdAt, updatedAt, __v})

当我尝试渲染来自数据库的对象({day} 请参阅下面的反应组件)时出现以下错误:

Error: Objects are not valid as a React child (found: object with keys {_id, date, createdAt, updatedAt, __v}). If you meant to render a collection of children, use an array instead.

有问题的对象如下所示:

{
  "_id": "5fdf554b88f52f520c93a16e",
  "date": "2020-12-20T10:00:00.133Z",
  "createdAt": "2020-12-20T13:44:43.934Z",
  "updatedAt": "2020-12-20T13:44:43.934Z",
  "__v": 0
}

下面是我的代码:

路由器:

dayRouter.get(
  '/:id',
  expressAsyncHandler(async (req, res) => {
    const day = await Day.findOne({ _id: req.params.id })
    if (day) {
      res.send(day);
    } else {
      res.status(404).send('Booking Not Found.');
    }
  })
);
export default dayRouter;

Redux 动作:

export const detailsDate = (dayId) => async (dispatch) => {
  try {
    dispatch({ type: DATE_DETAILS_REQUEST, payload: dayId });
    const { data } = await Axios.get(`/api/day/${dayId}`);
    dispatch({ type: DATE_DETAILS_SUCCESS, payload: data });
  } catch (error) {
    dispatch({
      type: DATE_DETAILS_FAIL,
      payload:
        error.response && error.response.data.message
          ? error.response.data.message
          : error.message,
    });
  }
};

Redux-Reducer:

export function dateDetailsReducer(
    state = {loading: true}, action) {
    switch (action.type) {
      case DATE_DETAILS_REQUEST:
        return { loading: true };
      case DATE_DETAILS_SUCCESS:
        return { loading: false, day: action.payload };
      case DATE_DETAILS_FAIL:
        return { loading: false, error: action.payload };
      default:
        return state;
    }
  }

反应组件:

import { useDispatch, useSelector } from 'react-redux';
import { detailsDate } from '../actions/dateAction';

function BookingConfirmationScreen(props) {  

  const dayId = props.match.params.id;

  const dateDetails = useSelector((state) => state.dateDetails); //from Redux Store
  const { day } = dateDetails;

  const dispatch = useDispatch();
  useEffect(() => {

      dispatch(detailsDate(dayId));
    return () => {};
  }, [day,dispatch, dayId]);

  return (
    <h1> Booking {day}</h1>
  )
}

export default BookingConfirmationScreen;

我需要渲染的实际上是 {day.date} 但我知道那一天实际上是未定义的。就在那时我意识到 {day}

存在问题

day 是未定义的,因为您从服务器获取数据,因此呈现组件比异步调用更快。这就是为什么你在 reducer 中有 loading,当从服务器接收数据时它被设置为 false。从这样的状态中破坏 loading:

 const { day, loading } = dateDetails;
.
.
.

然后在您返回时执行此操作:

if(loading)
return <div> loading.. </div>
 return (
    <h1> Booking {day.date}</h1>
  )