嗨,我正在使用 react 構建一個商務應用程式,我想保存用戶最近進行的搜索,如下所示:
最近的搜索示例
如果你能幫助我,我將不勝感激
謝謝你
uj5u.com熱心網友回復:
您可以將其保存到本地存盤。
https://programmingwithmosh.com/react/localstorage-react/
請參閱此處的示例并嘗試將相同的內容應用于“歷史”本地存盤。
uj5u.com熱心網友回復:
像這樣將搜索保存到本地存盤中
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>
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/334974.html
標籤:javascript 节点.js 反应 输入 上下文 API
上一篇:與函式一起使用時陣列的問題
