首页 > 解决方案 > 反应钩子 setState 和 useContext 不起作用

问题描述

我正在尝试使用数组更新反应上下文

这是购物车上下文

import React, { useState } from "react";
 
import UniqueString from "../lib/unique-string";
import suspender from "../lib/suspender";
import db from '../db';
const uid = new UniqueString();

// set up the database when this function is called

// const CartDBContext = React.createContext(setUpDatabase())




const emptycart = {"454":{"test"}}

const CartContext = React.createContext([emptycart]);


// function to get all meals 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());

// The component itself
function CartContextProvider({ children }) {
    // reading data from suspender
    const items = resource.data.read() || [];
    console.log("all items from suspender", items, resource)

    // state to store list of items in the object Store
    const [itemsList, setItemsList] = useState(items);

    // if the itemList is null, umnount the component
    // else return the appropriate JSX
    return (
        // pass the mealsList state and its setter as context values
        <CartContext.Provider value={{ itemsList, setItemsList }}>
            {children}
        </CartContext.Provider>
    );
}

export default CartContextProvider;
export { CartContext };

这是使用上下文的 index.jsx

import React, { useContext,useState,useEffect,useRef ,Suspense } from "react";

import CartContextProvider, { CartContext }  from "../components/CartContextProvider";

function Index(){


...
    const [itemsList, setItemsList] = useContext(CartContext);
    
 useEffect(() => { 
runIndexDb(data).then(async result => {
                            console.log("ItemList is ", itemsList)

                            console.log(result)
                            
                            
                            setItemsList(itemsList => [...itemsList, result]);
                        }) 
                        
      })


...
}

The print out of console.log 
for itemsList

ItemList is  {454: "test"}

result 

0: {id: "00010164533955", name: "Hilsinger Company Sport Band - Black", productimg: "http://i5.walmartimages.com/asr/44e902de-30f8-40f3…9fdb.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: 2, …}
1: {id: "00014381104394", name: "A House Divided: Season 1 (DVD)", productimg: "http://i5.walmartimages.com/asr/99cfec5c-634e-4e26…4465.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: "1", …}
2: {id: "00016500590958", name: "One A Day Men's 50+ Mini Gels, Multivitamins for Men, 80 Ct", productimg: "http://i5.walmartimages.com/asr/7d44d419-bd6f-4808…b7ea.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: "1", …}
3: {id: "00022141041599", name: "Mepps Dressed Aglia Inline Spinner, Silver & Gray, 1/4 oz", productimg: "http://i5.walmartimages.com/asr/a0ce2579-300a-4536…0d63.jpeg?odnHeight=180&odnWidth=180&odnBg=ffffff", unitofissue: "each", quantity: "1", …}
 

代码在 setItemsList 处引发错误

未处理的拒绝 (TypeError):setItemsList 不是函数

我尝试了许多不同的方法但没有解决方案

我做错了什么,如何使用上面的数组更新 itemsList?

标签: javascriptreactjsreact-hooks

解决方案


useContext返回一个对象而不是一个列表。如果你这样做,它应该可以工作

const { itemsList, setItemsList } = useContext(CartContext);


推荐阅读