简体   繁体   中英

React showing a blank screen without any error messages (context api used)

I'm building a react Amazon clone, so in order to give the user the ability to add a product into his basket (as the first version of all the future checkout system), I've used Context Api to manage this.

When I finished writing Context Api code and adding it to the index.js file so I could access the data I got a blank screen with absolutely no error messages. I don't know where is exactly the problem.

StateProvider.js

import React , { createContext, useContext, useReducer} from 'react'

export const StateContext = createContext();

export const StateProvider = ({reducer , initialValue, children}) => {
    <StateContext.Provider value={useReducer(reducer, initialValue)}>
        {children}
    </StateContext.Provider>
};

export const useStateValue = () => useContext(StateContext)

reducer.js

export const initialState = {
    basket: [], 
};

const reducer = (state, action) => {
    switch(action.type) {
        case "ADD_TO_BASKET":
            return{
                ...state,
                basket: [...state.basket, ...action.item]
            };
            default: 
            return state;
    };
};

export default reducer;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import { StateProvider } from './Special_components/StateProvider';
import reducer, { initialState } from './Special_components/reducer';

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
    <React.StrictMode>
        <StateProvider reducer={reducer} initialState={initialState} >
            <App />
        </StateProvider>
    </React.StrictMode>

)

Looks like you're providing props to the wrong component. Try this in index.js :

...

<StateProvider reducer={reducer} initialValue={initialState}>
  <App />
</StateProvider>

...

Also note how I renamed the prop to initialValue because that's what your StateProvider is expecting.

You forgot to add return in your StateProvider function

    export const StateProvider = ({reducer , initialValue, children}) => {
return (
 <StateContext.Provider value={useReducer(reducer, initialValue)}>
        {children}
    </StateContext.Provider>
)}
export const useStateValue = () => useContext(StateContext)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM