React 和 Firebase 项目计数器

React and Firebase item counter

我正在做一个小项目,允许用户在输入字段中输入项目,然后 increase/decrease 金额。所有数据都存储在 Firebase 中。当有多个项目时,当 increasing/decreasing 值时,前一个项目的计数值似乎覆盖了当前项目计数,因此值未准确更新。我认为这与我的计数状态设置方式有关?任何见解将不胜感激!

import "./App.css";
import firebase from "./firebase";
import { getDatabase, ref, push, set, onValue } from "firebase/database";
import { useEffect, useState } from "react";

import Form from "./Form";
import GroceryItem from "./GroceryItem";

function App() {
const [groceryItems, setGroceryItems] = useState([]);

const [userInput, setUserInput] = useState("");

let [count, setCount] = useState(1);

useEffect(() => {
const database = getDatabase(firebase);
const dbRef = ref(database);

onValue(dbRef, (response) => {
  const dbData = response.val();

  const dataArray = [];
  for (let key in dbData) {
    dataArray.push({
      key: key,
      itemName: dbData[key].itemName,
      amount: dbData[key].amount,
      apiImage: dbData[key].apiImage,
    });
  }
  setGroceryItems(dataArray);
});
}, []);

const handleUserInput = (event) => {
  setUserInput(event.target.value);
};

const handleSubmit = (event) => {
  event.preventDefault();

 if (!userInput) {
    alert("Please enter an item!");
  } else {
  const database = getDatabase(firebase);
  const dbRef = ref(database);

  push(dbRef, {
    itemName: userInput,
    amount: 1,
  });

  setUserInput("");
}
};

const handleIncreaseAmount = (key) => {
const database = getDatabase(firebase);
const dbRef = ref(database, `/${key}/amount`);

setCount((count += 1));
set(dbRef, count);
};

const handleDecreaseAmount = (key) => {
const database = getDatabase(firebase);
const dbRef = ref(database, `/${key}/amount`);

if (count < 1) {
  setCount(0);
} else {
  setCount((count -= 1));
  set(dbRef, count);
}
};

return (
 <div className="App">
  <Form
    handleSubmit={handleSubmit}
    userInput={userInput}
    handleUserInput={handleUserInput}
  />

  <ul className="listContainer">
    {groceryItems.map((item) => {
      return (
        <GroceryItem
          key={item.key}
          itemName={item.itemName}
          handleDecreaseAmount={() => handleDecreaseAmount(item.key)}
          handleIncreaseAmount={() => handleIncreaseAmount(item.key)}
          itemAmount={item.amount}
        />
      );
    })}
   </ul>
  </div>
 );
}

export default App;

firebase.js

import { initializeApp } from "firebase/app";

const firebaseConfig = {
apiKey: "AIzaSyBGZuLK5SwXFXRRL4f_IVHeaTfJD8lD5WQ",
authDomain: "grocery-list-app-a7047.firebaseapp.com",
projectId: "grocery-list-app-a7047",
storageBucket: "grocery-list-app-a7047.appspot.com",
messagingSenderId: "282873587634",
appId: "1:282873587634:web:b01a1570bac7ba6b6766ab",
};


const firebase = initializeApp(firebaseConfig);
export default firebase;

Form.js

const Form = ({ handleSubmit, userInput, handleUserInput }) => {
return (
<>
  <form action="" onSubmit={handleSubmit}>
    <label htmlFor="itemName" className="sr-only">
      Add grocery item
    </label>
    <input
      id="itemName"
      type="text"
      placeholder="Add item (e.g. apples)"
      value={userInput}
      onChange={handleUserInput}
    />
  </form>
 </>
 );
 };

 export default Form;

GroceryItem.js

const GroceryItem = ({
itemName,
itemAmount,
handleDecreaseAmount,
handleIncreaseAmount,
}) => {
return (
<li>
  <div className="rightItems">
    <p className="itemName">{itemName}</p>
  </div>
  <div className="btnContainer">
    <div className="updateBtns">
      <p className="itemAmount">{itemAmount}</p>
      <button onClick={handleDecreaseAmount}>Decrease amount</button>
      <button onClick={handleIncreaseAmount}>Increase amount</button>
    </div>
  </div>
</li>
);
};

export default GroceryItem;

感谢您的洞察力。我以前读过有关增量运算符的信息,但肯定会进一步研究!我实际上能够找到解决方案。我不需要设置状态变量,因为这是导致所有值被覆盖的问题。相反,我想出了这个似乎有效的方法

const handleIncreaseAmount = (key) => {
const database = getDatabase(firebase);
const dbRef = ref(database, `/${key}/amount`);

get(dbRef).then((snapshot) => {
  let currentCount = snapshot.val();
  currentCount = currentCount + 1;
  set(dbRef, currentCount);
});
};


const handleDecreaseAmount = (key) => {
const database = getDatabase(firebase);
const dbRef = ref(database, `/${key}/amount`);

get(dbRef).then((snapshot) => {
  let currentCount = snapshot.val();
  if (currentCount > 1) {
    currentCount = currentCount - 1;
    set(dbRef, currentCount);
  }
 });
};