首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >×TypeError:无法读取未定义属性的“菜谱”

×TypeError:无法读取未定义属性的“菜谱”
EN

Stack Overflow用户
提问于 2020-07-29 19:09:09
回答 3查看 265关注 0票数 1

救命啊!!

我使用react创建了一个web应用程序,并将它与节点js连接起来。

在那里,我需要将一个菜的状态传递给DishDetail组件,不管它是否在喜爱中。如果不受欢迎的话。我得把它标记成最喜欢的。每当一个人点击任何一个菜使它最喜欢,一个条目将被添加到收藏中的用户id和盘id

但是,每当一个新用户第一次登录并尝试将盘作为最爱添加时,我就会遇到错误,即favorite={this.props.favorites.favorites.dishes.some((dish)×TypeError:无法读取未定义的 at => dish._id === match.params.dishId)}语句在MainComponent.js中和var收藏夹= FavoriteDish.js的props.favorites.favorites.dishes.map((dish)语句中的“菜品”属性。

MainComponent.js

代码语言:javascript
复制
const DishWithId = ({match}) => {
      if(this.props.favorites.favorites!=null) {
        if(Array.isArray(this.props.favorites.favorites)) {
          this.props.favorites.favorites=this.props.favorites.favorites[0];
        }
      }
      
      return(
        (this.props.auth.isAuthenticated && !this.props.favorites.isLoading)
        ?
        <DishDetail dish={this.props.dishes.dishes.filter((dish) => dish._id === match.params.dishId)[0]}
          isLoading={this.props.dishes.isLoading}
          errMess={this.props.dishes.errMess}
          comments={this.props.comments.comments.filter((comment) => comment.dish === match.params.dishId)}
          commentsErrMess={this.props.comments.errMess}
          postComment={this.props.postComment}
          favorite={this.props.favorites.favorites.dishes.some((dish) => dish._id === match.params.dishId)}
          postFavorite={this.props.postFavorite}
          />
        :
        <DishDetail dish={this.props.dishes.dishes.filter((dish) => dish._id === match.params.dishId)[0]}
          isLoading={this.props.dishes.isLoading}
          errMess={this.props.dishes.errMess}
          comments={this.props.comments.comments.filter((comment) => comment.dish === match.params.dishId)}
          commentsErrMess={this.props.comments.errMess}
          postComment={this.props.postComment}
          favorite={false}
          postFavorite={this.props.postFavorite}
          />
      );
    } 
    <Route path="/menu/:dishId" component={DishWithId} />
    <PrivateRoute exact path="/favorites" component={() => <Favorites favorites {this.props.favorites} deleteFavorite={this.props.deleteFavorite} />} />

DishDetail.js

代码语言:javascript
复制
const DishDetail = (props) => {
    return <RenderDish dish={props.dish} favorite={props.favorite} postFavorite={props.postFavorite} />
}

function RenderDish({dish, favorite, postFavorite}) {
    return(
        <div className="col-12 col-md-5 m-1">
            <FadeTransform in 
                transformProps={{
                    exitTransform: 'scale(0.5) translateY(-50%)'
                }}>
                <Card>
                    <CardImg top src={baseUrl + dish.image} alt={dish.name} />
                    <CardImgOverlay>
                        <Button outline color="primary" onClick={() => favorite ? console.log('Already favorite') : postFavorite(dish._id)}>
                            {favorite ?
                                <span className="fa fa-heart"></span>
                                : 
                                <span className="fa fa-heart-o"></span>
                            }
                        </Button>
                    </CardImgOverlay>
                    <CardBody>
                        <CardTitle>{dish.name}</CardTitle>
                        <CardText>{dish.description}</CardText>
                    </CardBody>
                </Card>
            </FadeTransform>
        </div>
    );

}

FavoriteDish.js

代码语言:javascript
复制
    if (props.favorites.favorites) {
       if(Array.isArray(props.favorites.favorites))
          props.favorites.favorites=props.favorites.favorites[0];
       var favorites = props.favorites.favorites.dishes.map((dish) => {
         return (
             <div key={dish._id} className="col-12 mt-5">
                 <RenderMenuItem dish={dish} deleteFavorite={props.deleteFavorite} />
             </div>
         );
      });
   }

最爱的减速器

代码语言:javascript
复制
import * as ActionTypes from './ActionTypes';

export const favorites = (state = {
        isLoading: true,
        errMess: null,
        favorites: null
    }, action) => {
    switch(action.type) {
        case ActionTypes.ADD_FAVORITES:
            return {...state, isLoading: false, errMess: null, favorites: action.payload};

        case ActionTypes.FAVORITES_LOADING:
            return {...state, isLoading: true, errMess: null, favorites: null};

        case ActionTypes.FAVORITES_FAILED:
            return {...state, isLoading: false, errMess: action.payload, favorites: null};

        default:
            return state;
    }
}

ActionCreator.js

代码语言:javascript
复制
export const fetchFavorites = () => (dispatch) => {
    dispatch(favoritesLoading(true));

    const bearer = 'Bearer ' + localStorage.getItem('token');

    return fetch(baseUrl + 'favorites', {
        headers: {
            'Authorization': bearer
        },
    })
    .then(response => {
        if (response.ok) {
            return response;
        }
        else {
            var error = new Error('Error ' + response.status + ': ' + response.statusText);
            error.response = response;
            throw error;
        }
    },
    error => {
        var errmess = new Error(error.message);
        throw errmess;
    })
    .then(response => response.json())
    .then(favorites => dispatch(addFavorites(favorites)))
    .catch(error => dispatch(favoritesFailed(error.message)));
}

export const favoritesLoading = () => ({
    type: ActionTypes.FAVORITES_LOADING
});

export const favoritesFailed = (errmess) => ({
    type: ActionTypes.FAVORITES_FAILED,
    payload: errmess
});

export const addFavorites = (favorites) => ({
    type: ActionTypes.ADD_FAVORITES,
    payload: favorites
});
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2020-07-29 19:24:39

Ciao,您可以修改这一行(在DishWithId中):

代码语言:javascript
复制
(this.props.auth.isAuthenticated && !this.props.favorites.isLoading)

通过以下方式:

代码语言:javascript
复制
(this.props.auth.isAuthenticated && !this.props.favorites.isLoading && this.props.favorites.favorites)

这一行(在FavoriteDish.js中):

代码语言:javascript
复制
var favorites = props.favorites.favorites.dishes.map((dish)...

通过以下方式:

代码语言:javascript
复制
if (props.favorites.favorites) {var favorites = props.favorites.favorites.dishes.map((dish)...}
票数 1
EN

Stack Overflow用户

发布于 2020-07-30 08:15:51

从乔瓦尼·埃斯波西托那里得到的。

我刚换了一行:- favorite={this.props.favorites.favorites.dishes.some((dish) => dish._id === match.params.dishId)}

对此:- favorite={this.props.favorites.favorites ? this.props.favorites.favorites.dishes.some((dish) => dish._id === match.params.dishId): false}

票数 2
EN

Stack Overflow用户

发布于 2020-07-30 13:44:59

检查收藏夹中的条件,以防“宠儿”未定义。它会自动发送假的..。

代码语言:javascript
复制
favorite={this.props.favorites.favorites ? this.props.favorites.favorites.dishes.some((dish) => dish._id === match.params.dishId): false}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63160806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档