【问题标题】:Save the previous search when I go back with the page React当我返回页面 React 时保存之前的搜索
【发布时间】:2021-06-17 09:08:20
【问题描述】:

执行搜索时,我的应用会通过 API 返回结果。每个结果都有一个详细链接。单击链接并返回我搜索的内容未保存,搜索栏为空。您必须重写先前的搜索以选择另一个结果。我希望在返回时保存常规搜索。

function GoogleBooksSearch() {
    const [book, setBook] = useState("");
    const [result, setResult] = useState([]);
    const apiKey = ("MY API")

    function handleChange(event) {
        const book = event.target.value;
        console.log(event.target.value);
        setBook(book);
    }
    function handleSubmit(event) {
        event.preventDefault();
        axios.get("https://www.googleapis.com/books/v1/volumes?q=" + book + "&key=" + apiKey + "&maxResults=20")
            .then(data => {
                console.log(data.data.items);
                setResult(data.data.items);
            })
    }

    return (
        <div>
            <div className="hero-container">
                <h1>Search your book</h1>
                <p>Discover the best books ever</p>
                <form onSubmit={handleSubmit}>
                    <div className='container'>
                        <div>
                            <input onChange={handleChange} className="form" autoFocus placeholder="Enter the title of the book" type="text" />
                            <div style={{ marginTop: '20px' }}></div>
                            <div className='d-grid gap-2 '>
                                <input type="submit" value="SEARCH" className="btn btn-primary btn-lg mx-auto" />
                            </div>


                        </div>
                    </div>
                </form>
            </div>

我正在使用 .map 函数过滤结果,并使用 react-router 链接打开“详细信息”页面。

{result.map(book => ( ------

                                <Link className="btn btn-primary mt-auto"
                                    to={
                                        pathname: '/details',
                                 }>
                                    View
                                </Link>

【问题讨论】:

    标签: reactjs search react-router react-hooks


    【解决方案1】:

    我建议实现一个缓存库并使用它的重新隐藏过程,它会更高效并且具有更高的兼容性,但是对于一种快速的hackish方式实现方式这是为了将您的搜索查询及其结果保存在 localStorage(即使在浏览器关闭后仍然存在)或 sessionStorage(可以是特定于会话的),并在渲染搜索组件时从 Session/Local 存储中恢复状态。

    此外,您还可以通过使用 React Memo hooks 来使用 Memorization 带缓存的 momo 组件,提高稳定性和性能

    这样的事情可以帮助你(关注 cmets

    //PERSITST THE SEARCH HERE
      const {searchQuery,searchResults} = JSON.parse(window.sessionStorage.getItem("searchDetails"));
      
       const [book, setBook] = useState(searchQuery ? searchQuery : "" );
        const [result, setResult] = useState( searchResults ? searchResults:[]);
        const apiKey = ("MY API")
        
        function handleChange(event) {
            const book = event.target.value;
            console.log(event.target.value);
            setBook(book);
        }
        function handleSubmit(event) {
            event.preventDefault();
            axios.get("https://www.googleapis.com/books/v1/volumes?q=" + book + "&key=" + apiKey + "&maxResults=20")
                .then(data => {
                    console.log(data.data.items);
                    setResult(data.data.items);
    
    // STORE THE DATA HERE 
                   window.sessionStorage.setItem("searchDetails",JSON.stringify({searchQuery:book,searchDetails:data.data.items}))
                })
        }
    
        return (
            <div>
                <div className="hero-container">
                    <h1>Search your book</h1>
                    <p>Discover the best books ever</p>
                    <form onSubmit={handleSubmit}>
                        <div className='container'>
                            <div>
                                <input onChange={handleChange} className="form" autoFocus placeholder="Enter the title of the book" type="text" />
                                <div style={{ marginTop: '20px' }}></div>
                                <div className='d-grid gap-2 '>
                                    <input type="submit" value="SEARCH" className="btn btn-primary btn-lg mx-auto" />
                                </div>
    
    
                            </div>
                        </div>
                    </form>
                </div>

    【讨论】:

    • 谢谢,但我有一个错误:TypeError: JSON.parse(...) is null
    • 嗨对不起,我忘了考虑最初它将为空请用以下行更改它:window.sessionStorage.getItem("searchDetails")? window.sessionStorage.getItem("searchDetails") : "{searchQuery:'',searchResults:''}" 它应该可以正常工作。
    • 您好,感谢您的帮助,现在我没有收到错误,但我的初始情况相同。
    • 你能在任何在线沙箱上设置最小的代码复制吗?我很乐意帮助你。我只是想确定你是否能够持久化数据。由于卸载,搜索组件可能正在重新呈现。
    • 你可以在这里看到我的项目:github.com/EmmE-L/React-Search-Books
    猜你喜欢
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2013-03-05
    • 1970-01-01
    相关资源
    最近更新 更多