无法在React中读取未定义的属性'props'

时间:2018-01-28 17:10:10

标签: javascript reactjs react-redux

我很惊讶。也许你能说清楚。

这是一个我无法理解的反应之谜:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import './style.css';

import FavoritesListItem from '../../components/FavoritesListItem';

class Favorites extends Component {
  handleSaveFavorites() {
    console.log(this.props.favoritesList);
  }

  handleClearFavorites() {
    localStorage.clear();
  }

  handleConsoleLogLocalFavorites() {
    console.log('without JSON.parse', localStorage.getItem('lastSavedFavourites'));
    console.log('with JSON.parse',JSON.parse(localStorage.getItem('lastSavedFavourites')));
  }

  render() {
    if (this.props.favoritesList.length === 0) {
      return (
        <p className="FavoritesListItem-text">
          There are no favorite recipes to show!
        </p>
      );
    }

    const favoritesListGenerator = this.props.favoritesList.map(oneFav => {
      const keyOneFav = _.uniqueId('favorite_');
      return (
        <FavoritesListItem key={keyOneFav} title={oneFav[0]} link={oneFav[1]} />
      );
    });

    return (
      <div>
        <div className="container">
          <div className="row justify-content-xl-center">
            <ul className="col-xl-12">{favoritesListGenerator}</ul>
            <button onClick={this.handleSaveFavorites}>Save</button>
            <button onClick={this.handleClearFavorites}>Clear</button>
            <button onClick={this.handleConsoleLogLocalFavorites}>Local</button>
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  return {
    favoritesList: state.favoritesList,
    readFavorites: state.readFavorites,
  };
}

export default connect(mapStateToProps, null)(Favorites);

为什么this.props.favoritesList工作正常并且在favoritesListGenerator内阅读数据,但同一this.props.favoritesList不想在handleSaveFavorites内工作?

错误的屏幕截图:

enter image description here

我不知道我还要添加什么:......

编辑:

所以我添加了

  constructor() {
    super();
    this.handleSaveFavorites = this.handleSaveFavorites.bind(this);
  }

到我的代码,现在可以了!

AND

我认为

<button onClick={() => this.handleSaveFavorites()}>Save</button>

也会有用!

0 个答案:

没有答案