我使用useContext并获得未定义的值。我该如何解决?

时间:2019-12-18 11:28:34

标签: javascript reactjs

我使用useContext并获得未定义的值。我该如何解决?谢谢。 如果我使用context.Consumer,一切都很好 ................................................... ................................................... ................................................... ............................ 我的应用文件

import React from 'react';
import './App.css';
import ListItem from './components/list-item/ListItem';
import {ListItemProvider} from './contexts/ListItemContext';


function App() {
  return (
    <ListItemProvider>
      <div className="App">
          Hello Reactjs
          <ListItem/>
      </div>
    </ListItemProvider>
  );
}

export default App;

我的上下文文件

import React, { useReducer, createContext } from "react";
import * as types from "../constants/listItemConstants";

const init_state = {
    items: [],
    isFetching: false,
    fetched: false,
    error: false,
    errorMsg: ""
};

const listItemReducer = (state, action) => {
    switch (action.type) {
        case types.GET_ITEMS_REQUEST:
            return {
                ...state,
                isFetching: true,
                fetched: false,
                error: false,
                errorMsg: ""
            };
        case types.GET_ITEMS_SUCCESS:
            return {
                ...state,
                items: action.payload.data,
                isFetching: false,
                fetched: true,
                error: false,
                errorMsg: ""
            };
        case types.GET_ITEMS_FAILURE:
            return {
                ...state,
                isFetching: false,
                fetched: false,
                error: true,
                errorMsg: action.payload.error.toString()
            };
        default:
            return state;
    }
};

const ListItemContext = createContext();

const ListItemProvider = ({ children }) => {
    const [state, dispatch] = useReducer(listItemReducer, init_state);
    return <ListItemContext.Provider value="hello i'm from list-item context">{children}</ListItemContext.Provider>;
};

export {
    ListItemContext,
    ListItemProvider
}

我的Listitem组件

import React, { useContext } from "react";
import {
    ListItemContext
} from "../../contexts/ListItemContext";

const ListItem = () => {
    const data = useContext(ListItemContext);
    return <div className='list-item-box'>Hello i'm list { typeof data}</div>;
};

export default ListItem;

0 个答案:

没有答案