【发布时间】:2021-12-10 08:47:39
【问题描述】:
【问题讨论】:
-
您想为该用户永久保存它吗?
-
在此处提供您的代码,以便我们能够重现
标签: javascript node.js reactjs input context-api
【问题讨论】:
标签: javascript node.js reactjs input context-api
您可以将其保存到本地存储。
https://programmingwithmosh.com/react/localstorage-react/
在此处查看示例并尝试将相同的内容应用于“历史”本地存储。
【讨论】:
将搜索保存到本地存储 就这样
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>
);
}
【讨论】: