我很惊讶。也许你能说清楚。
这是一个我无法理解的反应之谜:
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
内工作?
错误的屏幕截图:
我不知道我还要添加什么:......
编辑:
所以我添加了
constructor() {
super();
this.handleSaveFavorites = this.handleSaveFavorites.bind(this);
}
到我的代码,现在可以了!
AND
我认为
<button onClick={() => this.handleSaveFavorites()}>Save</button>
也会有用!