如何简化当前的React代码?

时间:2019-03-21 21:08:34

标签: reactjs

如何简化我的React代码?我觉得我没有写DRY React代码。

我有多个处理程序和setStates,以及Sorting函数..但是我可以使一个函数处理一个状态..并从那里对其进行排序吗?我将代码分成块和组件。

如何简化我的代码?有什么建议吗?

import React, { Component } from 'react';

import { getMovies } from '../services/fakeMovieService';

class Movies extends Component {
    state = {
        isSorted: false,
        movies: getMovies(),
        isDisabled: true,
    };

    componentDidMount() {
        console.log(this.state.movies);
    }

    // Display all movies but not the one selected.
    handleDelete = movie => {
        this.setState({
            movies: this.state.movies.filter(m => m._id !== movie._id),
            isDisabled: false,
        });

        console.log(`Movie ${movie.title} deleted.`);
    };

    // Sort all video's by title
    sortByTitle = () => {
        this.setState({
            movies: this.state.movies.sort((a, b) =>
                a.title.localeCompare(b.title)
            ),
            isDisabled: false,
        });

        console.log('sorted by title');
    };

    // Sort all video's by genre
    sortByGenre = () => {
        this.setState({
            movies: this.state.movies.sort((a, b) =>
                a.genre.name.localeCompare(b.genre.name)
            ),

            isDisabled: false,
        });

        console.log('sorted by genre.');
    };

    // sort all video's by stock size
    sortByStock = () => {
        this.setState({
            movies: this.state.movies.sort(
                (a, b) => a.numberInStock - b.numberInStock
            ),
            isDisabled: false,
        });

        console.log('sorted by stock size.');
    };

    // Sort all video's by rating score
    sortByRating = () => {
        this.setState({
            movies: this.state.movies.sort(
                (a, b) => a.dailyRentalRate - b.dailyRentalRate
            ),
            isDisabled: false,
        });

        console.log('sorted by rating sore.');
    };

    // Add class to the reset button based on the current filter state.
    resetButtonClass = () => {
        let btnClass = 'btn btn-sm btn-';
        btnClass += this.state.isDisabled ? 'warning' : 'primary';
        return btnClass;
    };

    // Reset the video's filter
    resetFilter = () => {
        this.setState({
            movies: [...getMovies()],
            isDisabled: true,
        });

        console.log('Reset movies database.');
    };

    render() {
        const { length: count } = this.state.movies;

        // Check if there are movies available.
        if (count === 0)
            return (
                <React.Fragment>
                    <h4>There are no movies in the database.</h4>
                    <button
                        type="button"
                        onClick={this.resetFilter}
                        className="btn btn-primary btn-sm">
                        Reset
                    </button>
                </React.Fragment>
            );

        return (
            <React.Fragment>
                <h5 className="pb-2">Showing {count} in the database.</h5>
                <table className="table table-hover table-striped table-dark">
                    <thead>
                        <tr>
                            <th>
                                <span onClick={this.sortByTitle}>Title</span>
                            </th>
                            <th>
                                <span onClick={this.sortByGenre}>Genre</span>
                            </th>
                            <th>
                                <span onClick={this.sortByStock}>Stock</span>
                            </th>
                            <th>
                                <span onClick={this.sortByRating}>Rate</span>
                            </th>
                            <th>
                                <button
                                    onClick={this.resetFilter}
                                    className={this.resetButtonClass()}
                                    disabled={this.state.isDisabled && true}>
                                    Reset filter
                                </button>
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.state.movies.map(movie => {
                            const {
                                _id,
                                title,
                                genre,
                                numberInStock,
                                dailyRentalRate,
                            } = movie;

                            return (
                                <tr key={_id}>
                                    <th>{title}</th>
                                    <td>{genre.name}</td>
                                    <td>{numberInStock}</td>
                                    <td>{dailyRentalRate}</td>
                                    <td>
                                        <button
                                            onClick={() =>
                                                this.handleDelete(movie)
                                            }
                                            className="btn btn-danger btn-sm">
                                            Delete
                                        </button>
                                    </td>
                                </tr>
                            );
                        })}
                    </tbody>
                </table>
            </React.Fragment>
        );
    }
}

export default Movies;

1 个答案:

答案 0 :(得分:1)

您可以通过使用更通用的排序功能使它更干燥:

// general sort function
sortBy = predicateFunction => {
    this.setState({
        movies: this.state.movies.sort( predicateFunction ),
        isDisabled: false,
    });
};

// and then call it
sortByRating = () => this.sortBy((a, b) => a.dailyRentalRate - b.dailyRentalRate)

sortByTitle = () => this.sortBy((a, b) =>
            a.title.localeCompare(b.title))

... etc