首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >用新数据覆盖本地存储

用新数据覆盖本地存储
EN

Stack Overflow用户
提问于 2021-08-24 22:02:39
回答 1查看 327关注 0票数 0

大家好,我创建了一个历史页面,这样用户就可以查看他们过去的搜索历史,所以我使用了本地存储。在历史记录页面上,我试图呈现停留在那里的数据,当我再次搜索api时,这些数据不会更改。相反,我希望它继续向页面中添加数据。我以为数据会继续添加到本地存储中的新数组中,但它会用新数据覆盖现有的数据。我试图阻止这件事,但我被困住了。这是我所有页面的代码

搜索页面

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
export default function SearchPage(props) {
        // creating state to fetch the api
    const [search, setSearch] = useState('')

    
    // this is my function to monitor the words that are put into the input so these keywords that only matches specific data
    // in the api and so one the data is fetched it renders the topic related to that keyword 
    const handleSearch = (event) => {
        setSearch(event.target.value)
    }


    const handleSubmit = (event) => {       
        event.preventDefault();
            // this is where I bring my useState variable to monitor the state of the key words in order to
            // target specific data from the api    
        let url = `http://hn.algolia.com/api/v1/search_by_date?query=${search}`; 
        axios
        .get(url)
        .then((response) => {
            const result = response.data.hits;
            // this pushes the data fetched from the api to the results page using history
            props.history?.push ({
                pathname: '/results', 
                state: result,
            });
        })
        // catching any errors to let me know if there is something going on in the .then function
        .catch((error) => {
            console.log(error)
            console.log('Error while fetching data!')
        })
    }

    return (
        <div>
            <div className="search-form-container">
                {/* my form in where I search data by keywords */}
                <form onSubmit={handleSubmit}> 
                    <input type='text' placeholder="search" onChange={handleSearch} value={search}/>
                    <button type="submit">Search</button>
                </form>
                <hr/>
                <Link to="/history">Your Search History</Link>
            </div>
        </div>
    )
}

结果页

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
export default function ResultsPage(props) {
    console.log(props)
    // the variable declared below is where I am bringing in the data through history from the api.
    const data = props.history.location.state;

    
        let storedData = localStorage.setItem('data', JSON.stringify(data))
        console.log(storedData)


    // being that I am using history, I can map through the array of objects on the results page as shown below and then render it
    const hitList = data.map((data, idx) => {
        return (
            <ul key={idx}>
                <div>
                  <li> Author: {data.author}</li> 
                  <li>Story Title: {data.story_title}</li> 
                  <li>Comment: {data.comment_text}</li>  
                  <li>Created on: {data.created_at}</li>  
                  <li></li>  
                </div>
                <hr/>
            </ul>
        )
    })

    return (
        <div>
            <Link to='/'><h1>Search</h1></Link> 
            <Link to='/history'><h1>Your History</h1></Link>
            {/* In order for me to show my data I first had to map through the array of objects and then put the variable "hitlist" in the return */}
            <h3>{hitList}</h3>
        </div>
    )
}

历史记录页

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
export default function SearchHistoryPage(item) {
        
        const storedData = JSON.parse(localStorage.getItem('data'));
        storedData.push(item);
        localStorage.setItem('data', JSON.stringify(storedData));
        console.log(storedData);                                    

        const searchHistory = storedData.map((data, idx) => {
            return (
                <ul key={idx}>
                  <li> Author: {data.author}</li> 
                  <li>Story Title: {data.story_title}</li> 
                  <li>Comment: {data.comment_text}</li>  
                  <li>Created on: {data.created_at}</li>  
                </ul>
            )
        })

    return (
        <div>
            <h2>{searchHistory}</h2>
        </div>
    )
}
EN

回答 1

Stack Overflow用户

发布于 2021-08-24 22:20:48

结果页中,只使用从搜索页面获取的结果覆盖localStorage 'data‘键。

您可以做的是在将新结果推入结果页之前获取“历史记录”(localStorage 'data'),而不是按以下方式在历史页中获取:

结果页

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
const data = props.history.location.state;

// ADD THESE 2 LINEs
const historicData = JSON.parse(localStorage.getItem('data'));
historicData.push(data)

// Store "historicData" instead of "data"
// let storedData = localStorage.setItem('data', JSON.stringify(data))
let storedData = localStorage.setItem('data', JSON.stringify(historicData))

console.log(storedData)

历史记录页

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
// Just use localStorage 'data'. 
// Do not modify anything in History page since you are not taking any actions here. 
const storedData = JSON.parse(localStorage.getItem('data'));
storedData.push(item);
// localStorage.setItem('data', JSON.stringify(storedData)); <-- REMOVE
// console.log(storedData); <-- REMOVE
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68917589

复制
相关文章
0基础转大数据行业做什么岗位?
很多想入门大数据的人一直处于迷茫阶段,不知道自己该不该转行学习大数据,不知道自己是否要转大数据。
加米谷大数据
2020/04/21
5210
0基础转大数据行业做什么岗位?
linux eval
eval 就是执行以下两个步骤 1.第一次,执行变量替换,类似与C语言的宏替代
雪影
2018/08/02
9090
Python - eval()
eval 的作用域就是 g 指定的这个字典,外面的 x = 10 被屏蔽掉了,eval 是看不见的,所以使用了 x 为 5 的值
小菠萝测试笔记
2021/09/14
9030
python compile、eval、
    compile()函数允许程序员在运行时刻迅速生成代码对象,然后就可以用exec 语句或者内建函数eval()来执行这些对象或者对它们进行求值。一个很重要的观点是:exec 和eval()都可以执行字符串格式的Python 代码。当执行字符串形式的代码时,每次都必须对这些代码进行字节编译处理。compile()函数提供了一次性字节代码预编译,以后每次调用的时候,都不用编译了。
py3study
2020/01/09
1.4K0
tensorflow: eval()探究
  如果你的代码要处理多个graph和 session,更直白的方式可能是显式调用Session.run():
JNingWei
2018/09/28
9140
JavaScript eval() 函数
该方法只接受原始字符串作为参数,如果 string 参数不是原始字符串,那么该方法将不作任何改变地返回。因此请不要为 eval() 函数传递 String 对象来作为参数。
阳光岛主
2019/02/19
8780
神奇的伊娃(eval),魔鬼的伊娃(eval)
eval() 函数功能非常强大,它可以接收一个字符串参数,当把一个字符串传递给 eval() 之后,eval() 会把这个字符串当成一个有效的表达式(所谓表达式就是 eval() 会把字符串的引号去掉,然后将中间的内容当成有效的代码)来求值,并返回计算结果:
编程文青李狗蛋
2019/08/08
1.1K0
eval builtin command
使用空格分隔每个参数,如果参数中含有变量,则替换为变量值,然后再将构造的命令交由 Shell 解释执行。它通常用于动态生成和执行命令,或者将字符串解释为可执行的 Shell 代码。
恋喵大鲤鱼
2023/10/12
2340
eval()函数解析
由于 JSON 语法是 JavaScript 语法的子集,JavaScript 函数 eval() 可用于将 JSON 文本转换为 JavaScript 对象。 eval() 函数使用的是 JavaScript 编译器,可解析 JSON 文本,然后生成 JavaScript 对象。 必须把文本包围在括号中,这样才能避免语法错误: var obj = eval ("(" + txt + ")");
闵开慧
2018/03/30
1.4K0
js中eval
例如处理json(请不要这样使用,正确的做法应该是使用JSON.parse(data)):
阿超
2022/08/21
7.4K0
js中eval
简单说 eval 函数
我觉得eval( )函数是一个比较有趣的函数,虽然我平常基本用不到它。但我们还是来说说吧!
FEWY
2019/05/26
1.1K0
python 的eval()函数
主要参考:https://blog.csdn.net/chowyoungyoung/article/details/78879926
用户7886150
2020/12/22
1.2K0
javascript当中eval用法
1)eval 例 4.1.1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> </head> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!-- /*马克-to-win:var scriptCode = "c = a * b"; var a = 5; var b = 10; var c = 2; eval(scriptCode); 以上的话就相当于: eval("c = a * b");===c = a * b eval是global的方法, */ var result = window.eval("1+2/4") ;//根据上面所说,result=1+2/4; document.write(result) var s="today=new Date();document.write(today.toLocaleString())" eval(s) //--> </SCRIPT> </BODY> </HTML> 例 4.1.2 <HTML> <HEAD> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <TITLE>在eclipse中直接open with火狐即可</TITLE> </HEAD> <BODY> <SCRIPT LANGUAGE="JavaScript"> <!-- //例1 var s = "2+31-18"; /*When the eval() function is called, it expects a string to be passed to it as its single argument value. The contents of that string should be syntactically correct executable script source text.*/ document.write(eval(s)); var s1 = "2+31a-18"; /* note that we must comment out the following statement, otherwise, it reports error.*/ //document.write(eval(s1)); //例2 eval("d =new Date();document.write(d.toLocaleString())") //eval()函数的参数为字符串,功能是将该字符串执行出来。体会“执行”的意思! //--> </SCRIPT> </BODY> </HTML>
马克java社区
2019/11/25
1.2K0
javascript当中eval用法
深入了解 Eval
在严格模式下,eval有自己的词法环境。因此,在eval内部声明的函数和变量在外部不可见:
公众号---人生代码
2021/03/16
7770
python3 eval()函数
eval()函数十分强大,官方demo解释为:将字符串str当成有效的表达式来求值并返回计算结果。
py3study
2020/01/03
1.1K0
Python eval 函数妙用
语法: eval(source, globals, locals) -> value
周小董
2019/03/25
8750
【Pycharm】IDE Eval Resetter 相关
IDE Eval Resetter 是 pengzhile 这位大佬写的一款插件。
AXYZdong
2022/01/16
1.6K0
【Pycharm】IDE Eval Resetter 相关
Python eval安全案例
关于Python的eval函数, 大家一致的避免使用。 但有时候必须使用, 怎么保证安全呢? 下面我用一个案例来避免eval潜在的风险。 当然这只是其中的一种。
用户1416054
2018/08/02
1.1K0
Python - eval 和 exec 函数
Python 支持通过 eval 函数执行字符串命令,本文记录相关内容。 eval eval() 函数用来执行一个字符串表达式,并返回表达式的值。 语法 以下是 eval() 方法的语法: eval(expression[, globals[, locals]]) 参数 expression – 表达式。 globals – 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。 locals – 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。 示例 a="[1,2,3,4,5]"
为为为什么
2022/08/04
7840
Global eval. What are the options?
David Flanagan最近写了一个关于全局eval的简单表达式,可以用一行式子表示: var geval = this.execScript || eval;        尽管看起来很简短,但是跨浏览器的兼容性并不好。仔细考虑了下这个话题,我觉得还有一些方法来实现代码的全局执行。而且有些方法--间接eval--并不为人所熟知,而且它们的内涵也不容易让人们所接受,本文主要介绍下该技术。        为了可以更清晰的讲解间接eval,我打算先回顾”全局eval“的方法,并回顾它们是如果起作用的,我也
欲休
2018/03/15
8440

相似问题

eval(dir()[0])在python中做什么

115

变量*读-eval*做什么?

22

return this || (0,eval)('this');

10

为什么[eval]在[eval][0]('code')中工作?

43

model.eval()在pytorch中做什么?

35
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文