简体   繁体   English

反应显示没有任何错误消息的空白屏幕(使用上下文 api)

[英]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.我正在构建一个 React Amazon 克隆,所以为了让用户能够将产品添加到他的购物篮中(作为所有未来结帐系统的第一个版本),我使用 Context Api 来管理它。

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.当我编写完 Context Api 代码并将其添加到index.js文件中以便我可以访问数据时,我得到了一个完全没有错误消息的空白屏幕。 I don't know where is exactly the problem.我不知道问题到底出在哪里。

StateProvider.js 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减速器.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 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 :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.另请注意我如何将道具重命名为initialValue ,因为这是您的StateProvider所期望的。

You forgot to add return in your StateProvider function您忘记在 StateProvider 函数中添加 return

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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