我创建了一个购物车上下文,我希望购物车在商品数量发生变化时重新呈现。我能够验证项目列表中的更改,但购物车没有重新呈现。这是我创建购物车上下文的方式
import React, { useState } from "react";
import UniqueString from "../lib/unique-string";
import suspender from "../lib/suspender";
import db from '../db';
import merge from 'lodash.merge'
import { useEffect } from "react";
const uid = new UniqueString();
const CartContext = React.createContext();
// function to get all items in the DB
async function getAllItemsFromDB() {
return new Promise((resolve, reject) => {
var allItems = db.table("cartitems").toArray().then((itemArry) => {
console.log("items in cart ",itemArry)
if (!itemArry || !itemArry.length) {
// array does not exist, is not an array, or is empty
// ⇒ do not attempt to process array
resolve([])
} else {
resolve(itemArry)
}
})
})
}
// using our suspender here
const resource = suspender(getAllItemsFromDB());
function CartContextProvider({ children }) {
// reading data from suspender
const items = resource.data.read();
console.log("ITEMS data type ", typeof(items))
// state to store list of items in the object Store
// set state to be the data retrieved from database
var [itemsList, setItemsList] = useState(items);
useEffect(() => {
console.log("ITEMSLIST CHANGED ", itemsList)
},[itemsList])
// return the context provider passing the itemsList state
// and its updator function as values of the context
return (
<CartContext.Provider value={{ itemsList, setItemsList }}>
{children}
</CartContext.Provider>
);
}
export default CartContextProvider;
export { CartContext };
这是我的cart.jsx,它使用了上面的cartcontex
import React, { useContext,useState,useEffect } from "react";
import { CartContext } from "./CartContextProvider";
import { Pane,Strong, Text,Table, Code, Heading,ListItem, Button,OrderedList,Avatar, Dialog } from 'evergreen-ui'
import Item from "./Item"; // we'll create this component soon
import db from '../db';
import CartDetailsContext from './context/systemContext'
import CartStatusContextProvider , { CartStatusContext } from "./CartStatus"
function Cart() {
const { itemsList, setItemsList } = useContext(CartContext);
const itemsinCart = itemsList.map((item) => {
console.log("item ==> ", item)
return <Item key={item.id} item={item} />;
});
// render list of all items
return <div className="menu">{itemsinCart}</div>;
}
const getCartLeftOver = (deleteId) => {
return new Promise((resolve, reject) => {
db.table('cartitems')
.delete(deleteId)
.then(() =>{
db.table("cartitems").toArray().then((itemArry) => {
console.log("letfover array ", itemArry)
resolve(itemArry)
})
})
})
}
// no item fall back component
function NoItemsFallback() {
return (
<div className="fallback">
<h1>:(</h1>
<h3>There are no items in cartitems.</h3>
<p>Use the form above to add some.</p>
</div>
);
}
export default Cart;
我与 useffect 中的 carcontex 提供商确认
console.log("ITEMSLIST CHANGED ", itemsList)
itemList 获取更新后的商品数量,但购物车不会像当 itemsList 状态改变时那样自动重新渲染。如何解决此问题并使购物车自动重新呈现?