51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

useContext错误:react__WEBPACK_IMPORTED_MODULE_2__.useContext(…)未定义。

英文:

useContext error: react__WEBPACK_IMPORTED_MODULE_2__.useContext(...) is undefined

问题 {#heading}

kitsDataContext.js

import { useQuery } from '@tanstack/react-query'
import axios from 'axios'
import { createContext } from 'react';

export const kitsDataContext = createContext();

//creates provider so content on the database can be accessible to all components
export const kitsDataProvider = ({ children }) => {

    const fetchKits = async () => {
        const response = await axios.get("https://localhost:5001/kitsDB");
        return response.data;
    };

    //saves JSON data on "data" variable
    function RQKitsDB() {
        const { isLoading, data } = useQuery("kitsDB", fetchKits);
        return { isLoading, data };
    };

    return (
        <kitsDataContext.Provider value={{ RQKitsDB }}>
            {children}
        </kitsDataContext.Provider>
    );
};

export default kitsDataProvider;

SerumRow.js

import "./row.css";
import { Button } from 'react-bootstrap';
import AddToCart from './AddToCart.js';

import { useContext } from 'react';
import { kitsDataContext } from './contexts/kitsDataContext.js';

import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { kitsDataProvider } from './contexts/kitsDataContext.js';

const queryClient = new QueryClient()

//complete row with all the data from the database, also adds AddToCart button below every kit
function SerumRowNoProviders() {

    //consume context
    const { RQKitsDB } = useContext(kitsDataContext);
    const { isLoading, data } = RQKitsDB();

    return (
        <div className="small-container">
            <h1>SERUM PRESETS</h1>
            <div className="row">
                <div className="col-3 text-center">
                    <img src="./images/WavSupply-Sidepce-Elysium-Loop-Kit-920x920.jpg" alt="Product 1" />
                    <div>{data?.aa[0]?.name}</div>
                    <div className="priceReact"></div>
                    <AddToCart />
                </div>
                <div className="col-3 text-center">
                    <img src="./images/WavSupply-Sidepce-Elysium-Loop-Kit-920x920.jpg" alt="Product 2" />
                    <div>{data?.aa[1]?.name}</div>
                    <div className="priceReact"></div>
                    <AddToCart />
                </div>
                <div className="col-3 text-center">
                    <img src="./images/WavSupply-Sidepce-Elysium-Loop-Kit-920x920.jpg" alt="Product 3" />
                    <div>{data?.aa[2]?.name}</div>
                    <div className="priceReact"></div>
                    <AddToCart />
                </div>
                <div className="col-3 text-center">
                    <img src="./images/WavSupply-Sidepce-Elysium-Loop-Kit-920x920.jpg" alt="Product 4" />
                    <div>{data?.aa[3]?.name}</div>
                    <div className="priceReact"></div>
                    <AddToCart />
                </div>
            </div>
            {/*takes user to page with all available kits */}
            <h1><button type="button" id="show-more" className="btn btn-outline-dark btn-lg">BROWSE ALL</button></h1>
        </div>
    );
}

//wraps SerumRowNoProviders() with needed Providers
function SerumRow() {
    return (
        <QueryClientProvider client={queryClient}>
            <kitsDataProvider>
                <SerumRowNoProviders />
            </kitsDataProvider>
        </QueryClientProvider>
    );
}

export default SerumRow;

index.js

const serumRow = document.getElementById("SerumRow");
root = ReactDOM.createRoot(serumRow);
root.render(
    <React.StrictMode>
        <SerumRow />
    </React.StrictMode>
);

The provided code appears to have some issues related to JSX syntax and the use of React Context. I've made some corrections in the code above. Make sure to import the necessary libraries (e.g., React, ReactDOM) at the top of your JavaScript file. 英文:

I'm fetching data with react-query and using Context API to make the fetched data available to other components:

kitsDataContext.js

import { useQuery } from &#39;@tanstack/react-query&#39;
import axios from &#39;axios&#39;
import { createContext } from &#39;react&#39;;
export const kitsDataContext = createContext();
//creates provider so content on the database can be accessible to all components
export const kitsDataProvider = ({children}) =&gt; {
const fetchKits = async () =&gt; {
const response = await axios.get(&quot;https://localhost:5001/kitsDB&quot;);
return response.data; 
};
//saves JSON data on &quot;data&quot; variable
function RQKitsDB(){
const { isLoading, data } = useQuery(&quot;kitsDB&quot;, fetchKits);
return { isLoading, data };
};
return( 
&lt;kitsDataContext.Provider value={{RQKitsDB}}&gt;
{children}
&lt;/kitsDataContext.Provider&gt;
);	
};
export default kitsDataProvider;

In another file, I consumed that data on a component, I also wrapped that component on the same file to make it ready to render on my index.js:

SerumRow.js

import &quot;./row.css&quot;
import {Button} from &#39;react-bootstrap&#39;;
import AddToCart from &#39;./AddToCart.js&#39;;
import { useContext } from &#39;react&#39;;
import { kitsDataContext } from &#39;./contexts/kitsDataContext.js&#39;
import { QueryClient, QueryClientProvider } from &#39;@tanstack/react-query&#39;
import { kitsDataProvider } from &#39;./contexts/kitsDataContext.js&#39;
const queryClient = new QueryClient()
//complete row with all the data from the database, also adds AddToCart button below every kit
function SerumRowNoProviders() {
//consume context
const { RQKitsDB } = useContext(kitsDataContext);
const { isLoading, data } = RQKitsDB();
return (
&lt;div className=&quot;small-container&quot;&gt;
&lt;h1&gt;SERUM PRESETS&lt;/h1&gt;
&lt;div className=&quot;row&quot;&gt;
&lt;div className=&quot;col-3 text-center&quot;&gt;
&lt;img src=&quot;./images/WavSupply-Sidepce-Elysium-Loop-Kit-920x920.jpg&quot; alt=&quot;Product 1&quot; /&gt;
&lt;div&gt;{data.aa[0].name}&lt;/div&gt;
&lt;div className=&quot;priceReact&quot;&gt;&lt;/div&gt;
&lt;AddToCart /&gt;
&lt;/div&gt;
&lt;div className=&quot;col-3 text-center&quot;&gt;
&lt;img src=&quot;./images/WavSupply-Sidepce-Elysium-Loop-Kit-920x920.jpg&quot; alt=&quot;Product 2&quot; /&gt;
&lt;div&gt;{data.aa[1].name}&lt;/div&gt;
&lt;div className=&quot;priceReact&quot;&gt;&lt;/div&gt;
&lt;AddToCart /&gt;
&lt;/div&gt;
&lt;div className=&quot;col-3 text-center&quot;&gt;
&lt;img src=&quot;./images/WavSupply-Sidepce-Elysium-Loop-Kit-920x920.jpg&quot; alt=&quot;Product 3&quot; /&gt;
&lt;div&gt;{data.aa[2].name}&lt;/div&gt;
&lt;div className=&quot;priceReact&quot;&gt;&lt;/div&gt;
&lt;AddToCart /&gt;
&lt;/div&gt;
&lt;div className=&quot;col-3 text-center&quot;&gt;
&lt;img src=&quot;./images/WavSupply-Sidepce-Elysium-Loop-Kit-920x920.jpg&quot; alt=&quot;Product 4&quot; /&gt;
&lt;div&gt;{data.aa[3].name}&lt;/div&gt;
&lt;div className=&quot;priceReact&quot;&gt;&lt;/div&gt;
&lt;AddToCart /&gt;
&lt;/div&gt;
&lt;/div&gt;
{/*takes user to page with all available kits */}
&lt;h1&gt;&lt;button type=&quot;button&quot; id=&quot;show-more&quot; className=&quot;btn btn-outline-dark btn-lg&quot;&gt;BROWSE ALL&lt;/button&gt;&lt;/h1&gt;
&lt;/div&gt;
);
}
//wraps SerumRowNoProviders() with needed Providers
function SerumRow() {
return (
&lt;QueryClientProvider client={queryClient}&gt;
&lt;kitsDataProvider&gt;
&lt;SerumRowNoProviders /&gt;
&lt;/kitsDataProvider&gt;
&lt;/QueryClientProvider&gt;
);
}
export default SerumRow;

Finally, I render it on the HTML:

index.js

const serumRow = document.getElementById(&quot;SerumRow&quot;);
root = ReactDOM.createRoot(serumRow);
root.render(
&lt;React.StrictMode&gt;
&lt;SerumRow /&gt;
&lt;/React.StrictMode&gt;
);

The problem is that I am getting an error regarding useContext():

react__WEBPACK_IMPORTED_MODULE_2__.useContext(...) is undefined
SerumRowNoProviders@http://localhost:3000/main.b08a434d0e7255432ca0.hot-update.js:44:56
renderWithHooks@http://localhost:3000/static/js/bundle.js:22007:31
mountIndeterminateComponent@http://localhost:3000/static/js/bundle.js:25293:17
beginWork@http://localhost:3000/static/js/bundle.js:26589:20
callCallback@http://localhost:3000/static/js/bundle.js:11599:18
invokeGuardedCallbackDev@http://localhost:3000/static/js/bundle.js:11643:20
invokeGuardedCallback@http://localhost:3000/static/js/bundle.js:11700:35
beginWork$1@http://localhost:3000/static/js/bundle.js:31574:32
performUnitOfWork@http://localhost:3000/static/js/bundle.js:30821:16
workLoopSync@http://localhost:3000/static/js/bundle.js:30744:26
renderRootSync@http://localhost:3000/static/js/bundle.js:30717:11
performSyncWorkOnRoot@http://localhost:3000/static/js/bundle.js:30409:38
flushSyncCallbacks@http://localhost:3000/static/js/bundle.js:18439:26
flushSync@http://localhost:3000/static/js/bundle.js:30513:11
scheduleRoot@http://localhost:3000/static/js/bundle.js:31880:18
./node_modules/react-refresh/cjs/react-refresh-runtime.development.js/performReactRefresh/&lt;@http://localhost:3000/static/js/bundle.js:33918:21
performReactRefresh@http://localhost:3000/static/js/bundle.js:33903:29
./node_modules/@pmmmwh/react-refresh-webpack-plugin/lib/runtime/RefreshUtils.js/createDebounceUpdate/enqueueUpdate/refreshTimeout&lt;@http://localhost:3000/static/js/bundle.js:807:17

Removing the useContext() call allows it to compile correctly, so it's clear that the error relates to that. I thought the cause was axios.get() not fetching the data quickly enough (as it is an async function).<br>
so as you can see I used the await operator but that didn't help.

答案1 {#1}

得分: 1

你可以尝试将上下文提供程序移到SerumRow.js组件内的index.js中,在React.StrictMode包装器内。 英文:

you can try to move the context provider to wrap SerumRow.js component inside index.js inside React.StrictMode wrapper

答案2 {#2}

得分: 1

这有点棘手。

问题在于 kitsDataProvider 不是一个组件,因为首字母 k 不是大写的 K(它们几乎相同 😊)。

如果你修复导入部分

import { KitsDataProvider } from './contexts/kitsDataContext.js';

// ...

<KitsDataProvider>
  <SerumRowNoProviders />
</KitsDataProvider>

上下文将提供给 SerumRowNoProviders

React 要求组件的首字母必须大写。 英文:

This was tricky.<br>

The issue is that kitsDataProvider is not a component because of the the first letter k is not capital K (they are almost the same 😂)

If you fix the import

import { KitsDataProvider } from &#39;./contexts/kitsDataContext.js&#39;

// ...

&lt;KitsDataProvider&gt;
  &lt;SerumRowNoProviders /&gt;
&lt;/KitsDataProvider&gt;

The context will be provided to SerumRowNoProviders.

> React requires that the first letter of components be capitalized


赞(0)
未经允许不得转载:工具盒子 » useContext错误:react__WEBPACK_IMPORTED_MODULE_2__.useContext(…)未定义。