未处理的拒绝类型错误:无法读取 null

时间:2021-06-07 09:27:43

标签: javascript reactjs react-router shopify shopify-app

enter image description here 当我点击添加到购物车时。我在终端中得到了这个。我卡住了。请帮忙。未处理的拒绝(类型错误):无法读取 null 的属性“id”。当我点击添加到购物车时。我在终端中得到了这个。我卡住了。请帮忙。未处理的拒绝(类型错误):当我单击添加到购物车时,无法读取 null 的属性“id”。我在终端中得到了这个。我卡住了。请帮忙。未处理的拒绝(类型错误):无法读取 null 的属性“id”。请注意我必须删除一些代码

class ShopProvider extends Component {

    state = {
        product: {},
        products: [],
        checkout: {},
        isCartOpen: false,
        isMenuOpen: false
    }

    componentDidMount() {
        if (localStorage.checkout_id) {
            this.fetchCheckout(localStorage.checkout_id)

        } else {
            this.createCheckout()
        } 
    }


    addItemToCheckout = async (variantId, quantity) => {
      const lineItemsToAdd = [
        {
          variantId,
          quantity: parseInt(quantity, 10)
        }
      ]


         const checkout = await client.checkout.addLineItems(this.state.checkout.id, lineItemsToAdd)
          this.setState({ checkout: checkout })
          console.log(checkout);
          this.openCart();
        }

  fetchAllProducts = async () => {
        const products = await client.product.fetchAll();
        this.setState({ products: products });
      };
    

    fetchProductWithHandle = async (handle) => {
        
        const product = await client.product.fetchByHandle(handle)
        this.setState({ product: product})
    }



    render() {
        return (
          <ShopContext.Provider
          value={{
            ...this.state,
            fetchAllProducts: this.fetchAllProducts,
            fetchProductWithHandle: this.fetchProductWithHandle,
            addItemToCheckout: this.addItemToCheckout,
            removeLineItem: this.removeLineItem,
            closeCart: this.closeCart,
            openCart: this.openCart,
            closeMenu: this.closeMenu,
            openMenu: this.openMenu
          }}
          >
            {this.props.children}
          </ShopContext.Provider>
        );
      }
    }
const ShopConsumer = ShopContext.Consumer

export { ShopConsumer, ShopContext };

export default ShopProvider



**Product page**


const ProductPage = () => {

    const { handle } = useParams();


    const { fetchProductWithHandle, addItemToCheckout, product } = useContext(ShopContext)

    useEffect(() => {
        fetchProductWithHandle(handle)
    }, [fetchProductWithHandle, handle])
    
    if (!product.title) return <div>Loading....</div>
        return (
            <Box>
                
                        <Button
                            onClick={() => addItemToCheckout(product.variants[0].id, 1)}
                        >
                            Add To Cart 
                        </Button>
                    
            </Box>
        )
    }

export default ProductPage;*

1 个答案:

答案 0 :(得分:0)

id 未定义,因为变体数组为空添加未定义的句柄条件

addItemToCheckout(product.variants[0]?product.variants[0].id:NaN,1)