反应firestore增量给出类型错误

时间:2019-10-24 01:38:15

标签: reactjs firebase google-cloud-firestore

我想在单击按钮时增加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;

1 个答案:

答案 0 :(得分:0)

您正在导出FirebaseApp实例。但是increment是在FieldValue常量上声明的。

因此,您还需要将firebase导入主文件,然后使用firebase.firestore.FieldValue.increment(1),如图here所示。