javascript - 在 ReactJS 的本地存储中获取空数据
问题描述
当我单击提交按钮时,我应该在本地存储中获取数据,但我的对象数组完全为空
我正在使用 titleDesMap 变量为 localArray 变量赋值,我正在获取数据但没有进入本地存储。
我的问题没有得到任何合适的答案。
任何人都可以请帮助...?
class Body extends React.Component {
titleDescMap = new Map();
localArray = new Array();
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChangeTitle = this.handleChangeTitle.bind(this);
this.handleChangeDescription = this.handleChangeDescription.bind(this);
this.handleCheckBoxChange = this.handleCheckBoxChange.bind(this);
}
state = {
countTodo: 1,
valueTitle: "",
valueDescription: "",
checkStatus: false,
routeLoading: false,
localStorageData: {},
};
statesStatus() {
return {
checkStatus: this.state.checkStatus,
};
}
handleChangeTitle(event) {
this.setState({
valueTitle: event.target.value,
});
}
handleChangeDescription(event) {
this.setState({
valueDescription: event.target.value,
});
}
handleCheckBoxChange(event) {
this.setState((prev) => ({ checkStatus: !prev.checkStatus }));
}
async handleSubmit(event) {
event.preventDefault();
this.setState({ routeLoading: true });
var previousTitle = this.titleDescMap.has(this.state.valueTitle);
// Sending data to database
// Checking if any title and desc is previously stored
if (previousTitle) {
alert("Please Enter Another Title (which you have never used)");
} else {
// Setting the values in title and description into Map
this.titleDescMap.set(this.state.valueTitle, this.state.valueDescription);
// Updating id as counter increases 1
const todoData = await axiosURL.get("/todo-data").then((res) => {
this.setState({ routeLoading: true });
return res.data;
});
this.setState({ routeLoading: false });
this.setState({
countTodo: todoData[todoData.length - 1].countTodo + 1,
});
// Starts here
this.localArray.push(this.titleDescMap);
localStorage["localStorageData"] = JSON.stringify(this.localArray);
console.log(JSON.parse(localStorage["localStorageData"]));
console.log(this.localArray);
//Ends here
}
this.props.history.push("/submit");
}
render() {
if (this.state.routeLoading) {
return (
<div className="spinner-design-outer">
<SpinnerRoundOutlined
className="spinner-design-inner"
color="#337AB7"
size="100px"
/>
</div>
);
}
return (
<div className="body-container">
<p className="body-direction">Fill To Save Your Todo</p>
<form method="post" onSubmit={this.handleSubmit}>
<div className="form-group">
<label>Title</label>
<input
type="text"
className="form-control"
placeholder="Title here"
value={this.state.valueTitle}
onChange={this.handleChangeTitle}
/>
</div>
<div className="form-group">
<label>Description</label>
<br />
<textarea
className="form-control"
placeholder="Description here"
rows="4"
cols="40"
value={this.state.valueDescription}
onChange={this.handleChangeDescription}
/>
</div>
<div className="form-check">
<input
type="checkbox"
className="form-check-input"
onChange={this.handleCheckBoxChange}
/>
<label className="form-check-label body-input-label">
Save Permanently
</label>
</div>
<button type="submit" className="btn btn-primary">
+ Add
</button>
</form>
</div>
);
}
}
export default withRouter(Body);
解决方案
本地存储不能像那样直接变异。它的行为更像 JS Map
,带有getItem
getter 和setItem
setter:
// Change this
localStorage["localStorageData"] = JSON.stringify(this.localArray);
// to this
localStorage.setItem("localStorageData", JSON.stringify(this.localArray));
// log like that
console.log(JSON.parse(localStorage.getItem("localStorageData")));
参考:https ://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
编辑:
另一个问题是您试图序列化 ( JSON.stringify()
) 包含Map
数据结构的数组。似乎它不能以这种方式工作(JSON 不支持Map
s - 它会将它们转换为空对象):您需要Map
先将 转换为数组(请参阅https://2ality.com/2015/08/es6-地图-json.html):
// change this
this.localArray.push(event.this.titleDescMap);
// to this
this.localArray.push([...event.this.titleDescMap]);
当您从 a 获取数据时localStorage
,您可能需要将此数组转换回 a Map
。
推荐阅读
- oracle - 通过获取用户输入的索引来搜索员工记录
- javascript - 在 MVC Web 应用程序的前端加密/解密私有 id 的最佳方法是什么?
- ios - Swift:UIViewController 实例未从 URLSession 委托方法接收更新
- python - 将 json 对象反序列化为 Faust 记录,其中 json 在键名中有连字符
- python - Selenium 无法在 iframe 中为字典定位元素
- python - 如何使用 excelwriter 在标题中换行?
- oracle - 在 Oracle 上的 JPA / Hibernate 中使用 UUID 作为 id
- centos7 - 可以在 PMAPI 中设置 Web 上下文编号吗?
- date - 使用 MM/DD/YY 的 TO_DATE 将字符串转换为日期会为 1970 年之前的日期提供错误值 [snowflake-cloud-data-platform]
- jupyter-notebook - 在 Julia 中添加包的问题