我目前有按状态更新用户输入并存储为值的方法,但是,每当用户指向另一个页面,关闭页面或刷新页面时,该值就会消失。我想将值永久存储在那里,直到用户更改其输入为止。我需要为此使用持久状态吗?我如何永久存储用户输入的值,直到用户更改它?
class Planning extends React.Component {
constructor() {
super()
this.state = {
title: '',
goal: '',
tech: '',
features: '',
details: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
})
}
handleSubmit(event) {
const {
title,
goal,
tech,
features,
details
} = this.state;
event.preventDefault();
this.setState({ title, goal, tech, features, details });
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div>
<label className="label-title">
Project Title:</label>
<input name="title" id="title" type="text" value={this.state.title} onChange={this.handleChange} required aria-required="true"/>
</div>
将handleChange
功能更改为:
handleChange(event) {
const { value, name } = event.target
localStorage[name] = value
this.setState({
[name]: value
})
}
并且您constructor
要:
constructor() {
super()
this.state = {
title: localStorage["title"],
goal: '',
tech: '',
features: '',
details: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
这不是很优雅,但可以工作。或者,您可以在卸载时保存到localStorage。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句