React Redux - Uncaught (в обещании) TypeError: невозможно прочитать свойство 'props' из undefined

Я новичок в React, имейте это в виду.

Я видел много людей, у которых возникли проблемы с привязкой ключевого слова "this", думаю, я понял это правильно, однако я все еще получаю сообщение об ошибке "Не могу прочитать свойство 'props' неопределенного ".

Я делаю что-то не так с моим приложением React + Redux, но не могу понять, что именно.

Вот мой код: Recipes_list.js

import React, { Component } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { getRecipe } from "../actions/index";

class RecipeList extends Component {
    constructor(props) {
        super(props);
        this.functionGetRecipe = this.functionGetRecipe.bind(this);
    }

    functionGetRecipe(recipe_id){
        this.props.getRecipe(recipe_id);
    }

    renderRecipes(recipeData) {     
        const publisher = recipeData.publisher;
        const recipe_id = recipeData.recipe_id;
        const title = recipeData.title;
        const source_url = recipeData.source_url;
        const image_url = recipeData.image_url;

        return (
            <tr onClick={this.props.functionGetRecipe(recipe_id)} key={recipe_id}>
                <td>{publisher}</td>
                <td>{title}</td>
                <td><a href={source_url}>View on original website</a></td>
                <td><img className="img-fluid" src={image_url} /></td>
            </tr>
        );
    }

    render() {
        if (!this.props.recipes) {
            return <div>Nothing to show yet</div>;
        }
        return (
            <table style={{width: "50%"}} className="table table-hover float-right">
                <thead>
                    <tr>
                        <th>Publisher</th>
                        <th>Title</th>
                        <th>Source</th>
                        <th>Image</th>
                    </tr>
                </thead>
                <tbody>
                    {this.props.recipes.map(this.renderRecipes)}
                </tbody>
            </table>    
        );
    }
}

function mapStateToProps(state){
    return { recipes: state.searchRecipes.recipes };
}

function mapDispachToProps(dispatch) {
    return bindActionCreators({ getRecipe }, dispatch);
}

export default connect(mapStateToProps, mapDispachToProps)(RecipeList);

Когда этот Контейнер / Компонент повторно отображается с массивом значений (this.props.recipes), консоль Chrome регистрирует следующую ошибку:

Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
at renderRecipes (bundle.js:36675)
at Array.map (<anonymous>)
at RecipeList.render (bundle.js:36746)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (bundle.js:7779)
at ReactCompositeComponentWrapper._renderValidatedComponent (bundle.js:7799)
at ReactCompositeComponentWrapper.wrapper [as _renderValidatedComponent] (bundle.js:1530)
at ReactCompositeComponentWrapper._updateRenderedComponent (bundle.js:7752)
at ReactCompositeComponentWrapper._performComponentUpdate (bundle.js:7736)
at ReactCompositeComponentWrapper.updateComponent (bundle.js:7665)
at ReactCompositeComponentWrapper.wrapper [as updateComponent] (bundle.js:1530)

Любая помощь приветствуется. Спасибо.

ПРИМЕЧАНИЕ: если я удалю весь код, связанный с действием, все будет работать нормально, таблица будет отображаться правильно

=============================================== ===============================

РЕДАКТИРОВАТЬ: изменение onClick = {this.props.functionGetRecipe (recipe_id)} на onClick = {this.functionGetRecipe (recipe_id)} возвращает мне следующую ошибку:

bundle.js:36675 Uncaught (in promise) TypeError: Cannot read property 'functionGetRecipe' of undefined

На всякий случай вот мой /actions/index.js:

import axios from 'axios';
const API_KEY = "***********************************";
export const GET_URL = `https://food2fork.com/api/get?key=${API_KEY}`;
export function getRecipe(recipeId) {
    const url = `${GET_URL}&Id=${recipeId}`;
    const request = axios.get(url);

    return {
        type: GET_RECIPE,
        payload: request
    };
}

=============================================== ===============================

РЕДАКТИРОВАТЬ2: Вот и все, теперь это работает. Вот изменение:

constructor(props) {
    super(props);
    this.renderRecipes = this.renderRecipes.bind(this);
}

person Scaccoman    schedule 05.12.2017    source источник
comment
Просто опечатка. Должно быть this.functionGetRecipe, а не this.props.functionGetRecipe   -  person hindmost    schedule 05.12.2017


Ответы (1)


Попробуйте заменить

<tr onClick={this.props.functionGetRecipe(recipe_id)} key={recipe_id}>

By :

<tr onClick={this.functionGetRecipe(recipe_id)} key={recipe_id}>

Изменить: я думаю, что объявление вашего метода functionGetRecipe() бесполезно, вы можете использовать this.props.getRecipe(recipe_id) напрямую

Изменить 2: вместо этого попробуйте привязать renderRecipes:

constructor(props) {
        super(props);
        this.renderRecipes = this.renderRecipes.bind(this);
    }
person Dyo    schedule 05.12.2017
comment
Если я сделаю это, журналы консоли Chrome: Uncaught (в обещании) TypeError: невозможно прочитать свойство functionGetRecipe из undefined - person Scaccoman; 05.12.2017