为什么我在部署中的表单提交会中断(React+Firestore)?



这在开发中工作正常,但是当我部署许多函数时,我的许多函数都会中断。 例如,我有一个将数据添加到数据库的表单,但是当我提交它时,它只是刷新页面,但数据永远不会进入数据库。

onSubmit = () => {
firebase.auth().onAuthStateChanged((user) => {
const { phoneNumber, points } = this.state;
let pointsToAdd = Number(points);
if(user) {
const docRef = database.collection('users').doc(user.uid).collection('customers').doc(phoneNumber);
docRef.set({
points: pointsToAdd
})
.then(() => {
console.log('success');
})
.catch((error) => {
console.log(error);
});
} else {
window.location.href = '/';
}
});
}

如果它刷新,则用户变量为 null。因此,您不得在已部署的版本上登录。只需先添加一个 firebase 登录函数,然后再调用该函数!

https://firebase.google.com/docs/auth/web/password-auth

我猜您没有登录非开发环境,当前实现将在找不到用户时简单地重定向。

作为对当前提交处理程序的反馈:我认为您希望在组件挂载时而不是在调用提交处理程序时侦听authStateChanged。相应地更新状态,并在访问正确的文档时使用状态中的用户。

例如:

componentDidMount () {
this.unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) this.setState({ user })
else window.location.href = '/'
})
}
componentWillUnmount () {
this.unsubscribe() // don't forget to unsubscribe when unmounting!
}
onSubmit = () => {
const { phoneNumber, points, user } = this.state;
let pointsToAdd = Number(points);
database.collection('users').doc(user.uid).collection('customers').doc(phoneNumber)
.set({
points: pointsToAdd
})
.then(() => {
console.log('success');
})
.catch((error) => {
console.log(error);
});
}

最新更新