我的排序功能是在渲染时自动调用的,而不是onClick

时间:2019-03-06 15:23:54

标签: javascript reactjs

我对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);

0 个答案:

没有答案