我想在单击按钮时增加Firestore数据库中数字字段的值。我已经设置了onClick按钮,但是当我单击它时,出现此错误:
TypeError:无法读取未定义的属性“ increment”
我找不到我做错了。
这是我的代码:
.post-content
我的Fire.js
import React,{useState,useEffect, useRef, useContext} from 'react'
import UserContext from './UserContext.js';
import fire from '../config/Fire';
import copper from '../img/coppernew.jpg'
function useTimes(){
const user = useContext(UserContext)
const [kullanici,setTimes] = useState([])
useEffect(()=>{
fire
.firestore()
.collection('kullanici')
.doc(user)
.onSnapshot((doc)=>{
const newTimes = doc.data()
setTimes(newTimes)
})
},[])
return kullanici
}
function upgradecopper(){
var userUid = fire.auth().currentUser.uid;
console.log(userUid);
var db = fire.firestore();
var copperincrease = db.collection("kullanici").doc(userUid);
copperincrease.update({
copper:fire.firestore.FieldValue.increment(1)
});
}
const Mine = () => {
const kullanici =useTimes()
return(
<div className="mine">
<div>
<ul className="a">
<ul className="dik2"><li><button onClick={()=>upgradecopper()}>Upgrade Copper Mine</button>(LVL: {kullanici.copper})</li><li><span><img src={copper} alt="copper"/></span></li></ul>
</ul>
</div>
<li>Account: <span>{kullanici.email} </span></li>
</div>
)
}
export default Mine
新的Fire.js文件:
import firebase from 'firebase/app';
import 'firebase/firestore'
import 'firebase/auth';
const config = {
(there is my api info)
};
const fire = firebase.initializeApp(config);
export default fire;
答案 0 :(得分:0)
您正在导出FirebaseApp
实例。但是increment
是在FieldValue
常量上声明的。
因此,您还需要将firebase
导入主文件,然后使用firebase.firestore.FieldValue.increment(1)
,如图here所示。