You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中Cake.jsx的Add_Products函数获取list返回undefined求助

React Context 取值异常:Add_Products函数中list返回undefined

问题描述

在Cake组件的Add_Products函数中,打印通过useContext(PdtList)获取的list时结果为undefined,但组件顶层的console.log(list)能正常输出数组。

相关代码

Cart.jsx

import { createContext, useEffect } from "react"
import Cake from "../About Section/Cake";
const PdtList = createContext();
export default function Cart() {
    let list = [
        {
            id: "52",
            name: "Doll cake"
            // images: image80
        },
        {
            id: "53",
            name: "Mixed Platte cake"
            // images: image81
        },
        {
            id: "54",
            name: "Pinata cake"
            // images: image82
        },
        {
            id: "55",
            name: "Bomb cake"
            // images: image83
        }
    ];
    return (
        <>
            <main className="align" >
                <h1>Thanks for shopping with us</h1>
                <PdtList.Provider value={list}>
                    <Cake />
                </PdtList.Provider>

            </main>
        </>
    )
}
export { PdtList };

Cake.jsx

import { PdtList } from "../Cart/Cart";
import { useContext, useState, useEffect } from "react";
export default function Cake(props) {
  const { name, images, bold, cut } = props;
  const list = useContext(PdtList);
  console.log(list);
  console.log(typeof(list));
  const Add_Products = (index) => {
    console.log('Add_Products called');
    let tobeAdded = { name, images, bold };
    console.log(list); // 此处打印list得到undefined
  };
  return (
    <>
      <main className="align unique">
        <img src={images} alt="" />
        <h1>{name}</h1>
        <div className="align2">
          <small>Rs {bold}</small>
          <small style={{ margin: "0px 10px" }}></small>
          <small
            style={{ "fontSize": "15px", textDecoration: "line-through" }}
          >
            Rs {cut}
          </small>
        </div>
        <button onClick={Add_Products} style={{ margin: "10px 0px" }}>
          Click here
        </button>
      </main>
    </>
  );
}

Birthday.jsx

import image60 from './assets/cake60.jpeg'
import image61 from './assets/cake61.jpeg'
import image62 from './assets/cake62.jpeg'
import image63 from './assets/cake63.jpeg'
import image64 from './assets/cake64.jpeg'
import image65 from './assets/cake65.jpeg'
import image66 from './assets/cake66.jpeg'
import image67 from './assets/cake67.jpeg'
import image68 from './assets/cake68.jpeg'
import image69 from './assets/cake69.jpeg'
import Cake from './Cake'
import { useContext } from "react"
import { PdtList } from "../Cart/Cart"
const pdtArray = [{
    id: '32',
    name: "Anniversary cake",
    images: image60
},
{
    id: '33',
    name: "Anniversary cake",
    images: image61
},
{
    id: '134',
    name: "Anniversary cake",
    images: image62
},
{
    id: '34',
    name: "Anniversary cake",
    images: image63
},
{
    id: '35',
    name: "Anniversary cake",
    images: image64
},
{
    id: '36',
    name: "Anniversary cake",
    images: image65
},
{
    id: '37',
    name: "Anniversary cake",
    images: image66
},
{
    id: '38',
    name: "Anniversary cake",
    images: image67
},
{
    id: '39',
    name: "Anniversary cake",
    images: image68
},
{
    id: '40',
    name: "Anniversary cake",
    images: image69
},
]
export default function Birthday(props) {
    const list = useContext(PdtList);
    console.log(list);
    const { title } = props;
    return (
        <>
            <main className='PDT_heading align' >
                <h1>{title}</h1>
                <div className="grid_system">
                    {
                        pdtArray.map((e) => {
                            const { name, images, id } = e;
                            return (
                                <Cake key={id} name={name} images={images} cut="232" bold="343" />
                            )
                        })
                    }
                </div>
            </main>
        </>
    )
}

问题分析

只有Cart组件渲染的Cake实例被PdtList.Provider包裹,能正常获取Context值;而Birthday组件中循环渲染的Cake实例,不在Provider的范围内,所以useContext(PdtList)拿到的是Context的默认值(创建时未传默认值,故为undefined)。点击Birthday中Cake的按钮时,执行的是该实例的Add_Products函数,此时的list自然是undefined。

解决方案

核心调整:统一Context作用范围

将所有需要访问PdtList的组件(包括Cart、Birthday及内部的Cake)都包裹在PdtList.Provider之下,示例如下:

  1. 在顶层组件(如App.jsx)中提供Context:
// App.jsx
import { PdtList } from './Cart/Cart';
import Cart from './Cart/Cart';
import Birthday from './Birthday/Birthday';

const list = [
    { id: "52", name: "Doll cake" },
    { id: "53", name: "Mixed Platte cake" },
    { id: "54", name: "Pinata cake" },
    { id: "55", name: "Bomb cake" }
];

function App() {
  return (
    <PdtList.Provider value={list}>
      <Cart />
      <Birthday title="Birthday Cakes" />
    </PdtList.Provider>
  );
}

export default App;
  1. 修改Cart组件,移除内部的Provider:
// Cart.jsx
import { createContext, useEffect } from "react"
import Cake from "../About Section/Cake";
const PdtList = createContext();
export default function Cart() {
    return (
        <>
            <main className="align" >
                <h1>Thanks for shopping with us</h1>
                <Cake />
            </main>
        </>
    )
}
export { PdtList };

兜底优化:设置Context默认值

创建Context时可以设置默认值,避免未被Provider包裹时出现undefined:

const PdtList = createContext([]); // 默认空数组

调整后,所有Cake实例都能正确获取Context的list值,Add_Products函数中的console.log(list)也能正常输出数组。


内容的提问来源于stack exchange,提问作者Ankit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 05:20:43