我对React和JS还是很陌生,并且在单击按钮时无法在组件中调用函数。我想在按钮上单击事件时调用sort函数,但是现在渲染后立即调用sort函数。如何使用我的按钮对onClick进行排序。任何帮助,将不胜感激。谢谢!
import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchCards } from "../actions/cardActions";
import Card from "../components/Card";
class CardList extends Component {
componentDidMount() {
this.props.fetchCards();
}
sortCards = cards => {
cards.sort(function(a, b) {
return a.front > b.front;
});
};
render() {
const cards = this.props.cards;
return (
<div className="CardList">
<button onClick={this.sortCards(cards)}>Sort Cards</button>
{cards.map(card => (
<Card
key={card.id}
cardId={card.id}
front={card.front}
back={card.back}
/>
))}
</div>
);
}
}
const mapStateToProps = state => {
return {
cards: state.card.all
};
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
fetchCards: () => {
dispatch(fetchCards(ownProps.deckId));
}
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(CardList);