React class 组件按钮 setState 排序未按预期工作

React class component button setState sorting not working as intended

import AuthorSidebar from "../SubPages/AuthorSidebar";
import ReactPaginate from 'react-paginate';
import { Card, Button } from 'react-bootstrap';

export default class Author extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            author: [],
            AuthorTempState: [],
            selectedPage: 0,
            Postsperpage: 4,
            PagesVisited: 0
        }
        this.handlePageClick = this.handlePageClick.bind(this);


    }

    async recievedData() {

        const res = await fetch(`https://api.quotable.io/authors?limit=30`);

        const data = await res.json();

        for (const element of data.results) {
            element.idfav = false;
        }


        data.results.sort((a, b) => (a._id > b._id) ? 1 : -1)

        this.setState({
            author: data.results,
            AuthorTempState: data.results
        });

    }



    componentDidMount() {


        if (localStorage.getItem('authors')) {
            this.setState({
                author: JSON.parse(localStorage.getItem('authors')),
                AuthorTempState: JSON.parse(localStorage.getItem('authors'))
            })
        } else {
            this.recievedData();
        }
    }

    componentDidUpdate(prevProps, prevState) {
        if (this.state.author !== prevState.author) {
            localStorage.setItem('authors', JSON.stringify(this.state.author))
        }


    }





    favBttn(Auth) {

        const filterData = this.state.AuthorTempState.filter(data => data._id !== Auth._id)

        Auth.idfav = true;

        const updateAuthor = [Auth, ...filterData];

        updateAuthor.sort((a, b) => (a._id > b._id) ? 1 : -1)

        this.setState({
            author: updateAuthor
        });

    }

    remfavBttn(Auth) {


        const filterData = this.state.AuthorTempState.filter(data => data._id !== Auth._id)

        Auth.idfav = false;

        const updateAuthor = [Auth, ...filterData]

        updateAuthor.sort((a, b) => (a._id > b._id) ? 1 : -1)

        this.setState({
            author: updateAuthor
        });

    }




    handlePageClick = (e) => {

        const SelectedPage = e.selected;
        const Offset = SelectedPage * this.state.Postsperpage;

        this.setState({
            selectedPage: SelectedPage,
            PagesVisited: Offset
        }, () => {
            this.recievedData();
        });
    };



    render() {



        const { author } = this.state;
        const PageCount = Math.ceil(author.length / this.state.Postsperpage);

        console.log(author)
        let sliced = author.slice(this.state.PagesVisited, this.state.PagesVisited + this.state.Postsperpage);

        return (

            <div className="AppWhole">
                <AuthorSidebar />
                <div className="App">
                    <div className="author">
                        {sliced.map(
                            (Author) => (
                                <div key={Author._id}>
                                    <Card style={{ margin: 20 }} border="dark" bg="light" text="grey">
                                        <Card.Body>
                                            <Card.Title>Name: {Author.name}
                                                {
                                                    (Author.idfav) ? (<Button size="sm" className='right' onClick={() => 
                                                        this.remfavBttn(Author)
                                                    }>Remove Favt.</Button >) : (<Button size="sm" className='right' onClick={() => 
                                                        this.favBttn(Author)
                                                    }>Add Favt.</Button >)
                                                }
                                            </Card.Title>
                                            <Card.Text>
                                                Bio: {Author.bio}
                                            </Card.Text>
                                        </Card.Body>
                                        <Card.Footer>Wiki: <a href='{Author.link}'>{Author.link}</a></Card.Footer>
                                    </Card>


                                </div>
                            ))}

                        <div >
                            <ReactPaginate
                                pageCount={PageCount}
                                onPageChange={this.handlePageClick}
                                previousLabel={"<<"}
                                nextLabel={">>"}
                                containerClassName={'paginationLinks'}
                                disabledClassName={'paginationDisabled'}
                                activeClassName={'paginationActive'}
                            />
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

所以我的页面是一个作者页面,它在我从 API 获取然后映射的每张卡片中显示不同的作者及其详细信息。 https://i.stack.imgur.com/QitTe.png

并且在点击后每张卡片中它变为删除收藏夹。被收藏的卡片使作者状态的 object 数组中的 idfav 为真,如果不被收藏则为假。第二页显示了所有最喜欢的作者。现在,在单击一张卡片以删除收藏夹然后单击另一张卡片也删除收藏夹后,前一张卡片会自动变为添加收藏夹。

请帮助我,我已经坚持了 2 周了。谢谢。

由于您需要更新列表中的单个对象 in-place,下面是您的操作方法,非常简单。


const bttn = (idfav) => Auth => this.setState({
  author: this.state.author.map(a => 
    a._id === Auth._id
      // When we find the auth to update, change its idfav
      ? {...a, idfav }
      : a
  });
const favBttn = bttn(true);
const remfavBttn = bttn(false);

或者如果您更喜欢未干燥的版本:

function async favBttn(Auth) {
 this.setState({
  author: this.state.author.map(a => 
    a._id === Auth._id
      // When we find the auth to update, change its idfav
      ? {...a, idfav: true }
      : a
  });
}

function async favBttn(Auth) {
 this.setState({
  author: this.state.author.map(a => 
    a._id === Auth._id
      // When we find the auth to update, change its idfav
      ? {...a, idfav: false }
      : a
  });
}