【问题标题】:Save recent searches react js保存最近的搜索反应 js
【发布时间】:2021-12-10 08:47:39
【问题描述】:

您好,我正在使用 react 构建一个商务应用,我想保存用户最近进行的搜索:

Recent searches example

如果你能帮助我,我将不胜感激

谢谢

【问题讨论】:

  • 您想为该用户永久保存它吗?
  • 在此处提供您的代码,以便我们能够重现

标签: javascript node.js reactjs input context-api


【解决方案1】:

您可以将其保存到本地存储。

https://programmingwithmosh.com/react/localstorage-react/

在此处查看示例并尝试将相同的内容应用于“历史”本地存储。

【讨论】:

    【解决方案2】:

    将搜索保存到本地存储 就这样

    function App() {
      const [history,sethistory]= useState({})
    
      useEffect(()=>{
        recover();
      },[])
      const recover=()=>{
         let data = JSON.parse(localStorage.getItem('history'));
         this.setState({history: data.history});
      }
      const onChangeHandler =(e)=>{
            e.preventDefault();
    
            this.setState({input: e.target.value});
        }
    
      const saveToStorage=()=>{
            //local storage only takes in key value pair so you would have to serialize it.
            let history = this.state.history ? this.state.history : {history: []};
    
            history.history.push({text:this.state.input, link:'store linke here'});
    
            localStorage.setItem('history', JSON.stringify(history));
      }
      return (
      <div>
        <input onChange={onChangeHandler}/>
          <Button onClick={saveToStorage}>
            Save
          </Button>
          <div className="your-side-bar">
              {this.state.history ? this.state.history.map((item) => {
                  return (
                    //render as state changes
                    <Link to={item.link}>{item.text}</Link>
                    )
              }) : 'no history'}
            </div>
      </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 2012-11-13
      • 2018-10-02
      • 2012-12-28
      • 2018-06-16
      • 1970-01-01
      • 2012-09-16
      • 1970-01-01
      • 2012-04-15
      • 1970-01-01
      相关资源
      最近更新 更多