【问题标题】:React.js Functional Component Localhost ProblemReact.js 功能组件本地主机问题
【发布时间】:2022-01-15 06:11:47
【问题描述】:

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

在每张卡片中点击后,它会变为删除收藏夹。收藏的卡片使作者状态的对象数组中的 idfav 为真,如果不收藏则为假。还有一个第二页显示了所有最喜欢的作者。现在我首先将它作为作者状态的本地存储传递下来,但是如果我单击按钮,无论按钮是添加还是删除,所有其他卡/数组都被删除并且只有卡在我的第二次重新加载之后我选择的按钮会显示出来。

    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;

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

【问题讨论】:

    标签: javascript reactjs web local-storage use-effect


    【解决方案1】:

    好的,一旦我阅读了您的整个代码,然后阅读了您的问题,就很清楚出了什么问题。问题就在这里

        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)
        }
    

    【讨论】:

    • 非常感谢您指出这一点,但是如何从 getAuthors 函数之外的 API 获取数据并进入 AuthorTempState?
    • 所以你想要的只是检查localStorage是否有数据,如果没有进行API调用。如果它有数据,则使用它。对吗?
    • 没错!!
    • getAuth 中,当您拨打setAuthor(newAuthors); 时,请同时拨打setAuthorTempState
    • 天哪,我怎么强调都不过分感谢你。它终于完美地工作了。再次感谢您帮助这个菜鸟。我会赞成你的回答,但没有代表:(
    猜你喜欢
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2012-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多