嗨,我正在使用react构建一个商业应用程序,我想保存用户最近的搜索:
最近搜索示例
如果你能帮助我,我会很感激的
谢谢
可以保存到本地存储
https://programmingwithmosh.com/react/localstorage-react/
请参阅此处的示例,并尝试对"history"本地存储.
将搜索保存到本地存储就像那样
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>
);
}