简体   繁体   English

React.js 功能组件本地主机问题

[英]React.js Functional Component Localhost Problem

So my page is an Author page which shows different authors and their details in each card which I fetched from API and then mapped.所以我的页面是一个作者页面,它显示了我从 API 获取然后映射的每张卡片中的不同作者及其详细信息。 https://i.stack.imgur.com/eSD7u.png https://i.stack.imgur.com/eSD7u.png

And in each card after onclick it changes to Remove Favourite.在 onclick 之后的每张卡中,它会更改为删除收藏夹。 The card which is favourited makes the idfav true in the object array of the author state and false if not favourited.收藏的卡使作者 state 的 object 数组中的 idfav 为真,如果不收藏则为假。 And there is a 2nd page which shows all the favourite authors.还有一个第二页显示了所有最喜欢的作者。 Now I am passing it down first as localstorage for the author state but it seems after my 2nd reload if I click on the button irrespective of whether or not the button is add or remove all the other cards/array is removed and only the card on which button I selected shows up.现在我首先将它作为作者 state 的本地存储传递下来,但是如果我单击按钮,无论按钮是否添加或删除,似乎在我第二次重新加载之后,所有其他卡/阵列都被删除并且只有卡在我选择的按钮出现了。

    const [author, setAuthor] = useState([]);


    const [AuthorTempState, setAuthorTempState] = useState([]);

    // pagination calculation
    const [PageNumber, setPageNumber] = useState(0);
    const [Postsperpage] = useState(4);
    const PagesVisited = PageNumber * Postsperpage;
    const pageCount = Math.ceil(author.length / Postsperpage);
    const changePage = ({ selected }) => {
        setPageNumber(selected);
    }


    const getAuthors = async () => {

        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)

        setAuthor(data.results);

        setAuthorTempState(data.results);


    }


    const saveAuth = () => {
        localStorage.setItem('authors', JSON.stringify(author));
    }

    const getAuth = () => {
        const newAuthors = JSON.parse(localStorage.getItem('authors'));
        if (newAuthors && newAuthors.length > 0) {
            setAuthor(newAuthors);
        } else {
            getAuthors();
        }
    }

    useEffect(() => {
        // console.log((author));

        if (author.length === 0) {
            getAuth();
        }

        saveAuth();

    }, [author]);



    const favBttn = (Auth) => {


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

        Auth.idfav = true;

        const updateAuthor = [Auth, ...filterData]

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


        setAuthor(updateAuthor)


    }

    const remfavBttn = (Auth) => {


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

        Auth.idfav = false;

        const updateAuthor = [Auth, ...filterData]

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

        setAuthor(updateAuthor);

    }

    const Author = author.slice(PagesVisited, PagesVisited + Postsperpage)



    return (
        <div className="AppWhole">
            <AuthorSidebar />
            <div className="App">
                <div className="author">
                    {Author.map(
                        (Author) => (
                            <div className="authors" key={Author._id}>
                                {
                                    (Author.idfav) ? (<button className='right' onClick={() => {
                                        remfavBttn(Author);
                                    }}>Remove Favt.</button >) : (<button className='right' onClick={() => {
                                        favBttn(Author);
                                    }}>Add Favt.</button >)
                                }
                                <p>Name: {Author.name}</p>
                                <p>Bio: {Author.bio}</p>
                                <p>Wiki: <a href='{Author.link}'>{Author.link}</a></p>
                            </div>
                        ))}

                    <div id='pageauthor'>
                        <ReactPaginate
                            pageCount={pageCount}
                            onPageChange={changePage}
                            previousLabel={"<<"}
                            nextLabel={">>"}
                            containerClassName={'paginationLinks'}
                            disabledClassName={'paginationDisabled'}
                            activeClassName={'paginationActive'}
                        />
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Authors;

Please help me I have been stuck on this for a week.请帮助我,我已经坚持了一周。 Thank you.谢谢你。

Okay, once I read your entire code and then read your issue made it pretty clear what's wrong.好的,一旦我阅读了您的整个代码,然后阅读了您的问题,就很清楚出了什么问题。 The issue is here问题在这里

    const favBttn = (Auth) => {

        // notice that you are using AuthorTempState to filter data
        // but do you remember initialising it when the data is found in local storage?
        // AuthorTempState is currently an empty array.
        const filterData = AuthorTempState.filter(data => data._id !== Auth._id)

        Auth.idfav = true;

        const updateAuthor = [Auth, ...filterData]

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

        setAuthor(updateAuthor)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM