reactjs - 反应如何在提交上存储状态值
问题描述
我试图在提交时将一个状态属性的值存储在另一个状态属性中,以便我可以将 URL 友好的 slug 提交到我的数据库。
以下是提交我的表单时调用的函数的一部分。目前,表单提交到数据库(Firestore)并且工作正常。但是,我需要收集用户输入到 streetAddress 的值,对其进行 slugify,然后使用我所在州的 slug 属性将其作为其自己的 slug 字段提交到我的数据库。
我遇到的问题是我不知道该怎么做。我尝试了几种方法并将 slug 提交到数据库,但始终为空值。以下是我尝试过的方法。
onSubmit = event => {
const { reviewTitle, reviewContent, streetAddress, cityOrTown,
countyOrRegion, postcode, startDate, endDate, landlordOrAgent, rating, slug } = this.state;
this.setState({
slug: streetAddress
})
// Creating batch to submit to multiple Firebase collections in one operation
var batch = this.props.firebase.db.batch();
var propertyRef = this.props.firebase.db.collection("property").doc();
var reviewRef = this.props.firebase.db.collection("reviews").doc();
batch.set(propertyRef, { streetAddress, cityOrTown,
countyOrRegion, postcode, slug,
uid });
batch.set(reviewRef, { startDate, endDate,
reviewTitle, reviewContent, rating,
uid });
batch.commit().then(() => {
this.setState({ ...INITIAL_STATE });
});
event.preventDefault();
};
谁能指出我正确的方向或告诉我我做错了什么?
解决方案
this.setState
是一个异步函数。所以你可以做的是在状态更新后调用回调函数。
this.setState({
slug: streetAddress
}, () => {
// Creating batch to submit to multiple Firebase collections in one operation
var batch = this.props.firebase.db.batch();
var propertyRef = this.props.firebase.db.collection("property").doc();
var reviewRef = this.props.firebase.db.collection("reviews").doc();
batch.set(propertyRef, {
streetAddress, cityOrTown,
countyOrRegion, postcode, slug,
uid
});
batch.set(reviewRef, {
startDate, endDate,
reviewTitle, reviewContent, rating,
uid
});
batch.commit().then(() => {
this.setState({ ...INITIAL_STATE });
});
event.preventDefault();
})
推荐阅读
- angular - fullcallendar 的角度选择器不起作用
- python - 如何在不重新启动机器的情况下修复 torch.cuda.is_available() False 问题?
- python - 当函数需要大数据结构作为参数时,如何有效地使用 Pool.starmap?
- vue.js - 如何以编程方式滚动元素而不是 vuetify 中的页面
- java - 为什么在 rDao.insert(log) 处出现未处理的 SQL 异常?
- google-cloud-platform - 如何为 GKE Ingress 分配静态 IP?
- python-3.x - Python:函数调用中的重复序列
- bash - 识别在 shell 中触发的并行进程的结束时间戳
- javascript - Javascript 循环中的 Promise
- javascript - 无法使用 puppeteer 导出异步功能