【问题标题】:Data won't show in Firestore Database [duplicate]数据不会显示在 Firestore 数据库中[重复]
【发布时间】:2022-01-21 12:41:05
【问题描述】:

我的待办事项应用中的数据不会显示在 Firestore 数据库中。我在终端中收到一条警告,上面写着“src/components/AddTodo.js 第 3:10 行中的警告:'collection' is defined but never used no-unused-vars”

在控制台中,它还显示 Uncaught (in promise) TypeError: firebase__WEBPACK_IMPORTED_MODULE_1_.db.collection is not a function。

AddToDo.JS

import React from 'react';
import { db } from '../firebase';
import { collection, addDoc } from 'firebase/firestore';

export default function AddTodo() {
  const [title, setTitle] = React.useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (title !== '') {
      await addDoc(db.collection('todos'), {  //<----Problem???--->//
        title,
        completed: false,
      });
      setTitle('');
    }
  };
  return (
    <form onSubmit={handleSubmit}>
      <div className="input_container">
        <input
          type="text"
          placeholder="Enter todo..."
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
      </div>
      <div className="btn_container">
        <button>Add</button>
      </div>
    </form>
  );
}

App.js

import './App.css';
import React from 'react';
import Title from './components/Title';
import AddTodo from './components/AddTodo';


function App() {
  return (
    <div className="App">
      <div>
        <Title />
      </div>
      <div>
        <AddTodo />
      </div>
    </div>
  );
}
export default App;

Firebase.js

import { initializeApp } from 'firebase/app';
import { getFirestore } from 'firebase/firestore';

//Firebase configuration
const firebaseConfig = {
  apiKey: 'AIzaSyCqranC2Lg9HXqoPPVAB3BVQqJFMAi569E',
  authDomain: 'fir-todo-ee3df.firebaseapp.com',
  projectId: 'fir-todo-ee3df',
  storageBucket: 'fir-todo-ee3df.appspot.com',
  messagingSenderId: '861076554800',
  appId: '1:861076554800:web:070895ff68a12d187f99f5',
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

export { db };

Title.js

import React from 'react';

export default function Title() {
  return (
    <div className="title">
      <h1>Todo App</h1>
    </div>
  );
}

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    我想出了自己的答案。这是一个语法问题,因为 Firebase 已更新到最新的 SDK 版本。第 11 行应该读作 等待 addDoc(collection(db, 'todos'), {

    【讨论】:

      【解决方案2】:

      看来您正在使用 v9(模块化)的 firebase。

      尝试使用此代码:

      await addDoc(collection(db, 'todos'), { 
              title,
              completed: false,
            });
      

      您可以查看 firebase documentation 了解有关如何添加新文档的更多信息。

      【讨论】:

      • 要走@chaz-carothers。我迟到了 2 分钟才发布我的答案,无论如何我希望你觉得我的答案有帮助。继续努力!
      猜你喜欢
      • 2018-12-09
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-22
      • 2016-04-22
      相关资源
      最近更新 更多