React - useContext 返回未定义

React - useContext is returning undefined

我尝试使用 React 上下文来管理我项目中的状态,但我似乎无法弄清楚为什么它返回未定义。我从我正在进行的另一个项目中复制了示例,看起来一切都应该正常工作。我似乎无法确定为什么不是。

这是我创建上下文的地方。

import React, { useState } from "react";

const initialTodos = [
  {
    id: 1,
    title: "Setup development environment",
    completed: true,
  },
  {
    id: 2,
    title: "Develop website and add content",
    completed: false,
  },
  {
    id: 3,
    title: "Deploy to live server",
    completed: false,
  },
];

export const TodoContext = React.createContext({
  todos: initialTodos,
  onChange: () => {},
});

const TodoContextProvider = (props) => {
  const [todos, setTodos] = useState(initialTodos);

  const handleChange = () => {
    console.log("clicked");
  };

  return (
    <TodoContext.Provider value={{ todos: todos, onChange: handleChange }}>
      {props.children}
    </TodoContext.Provider>
  );
};

export default TodoContextProvider;

这是我包装应用程序的地方。

import React from "react";
import ReactDOM from "react-dom";

import TodoContainer from "./components/TodoContainer";
import TodoContextProvider from "./context/TodoContext";

ReactDOM.render(
  <TodoContextProvider>
    <TodoContainer />
  </TodoContextProvider>,
  document.getElementById("root")
);

这是我的 TodoContainer。

import React, { useContext } from "react";
import TodosList from "./TodosList";
import Header from "./Header";
import TodoContext from "../context/TodoContext";

const TodoContainer = (props) => {
  const todoContext = useContext(TodoContext);

  console.log("todoContext", todoContext);

  return (
    <div>
      <Header />
      <TodosList />
    </div>
  );
};

export default TodoContainer;

这里是我尝试使用上下文的地方。

import React, { useContext } from "react";
import TodoItem from "./TodoItem";
import TodoContext from "../context/TodoContext";

const TodosList = (props) => {
  const todoContext = useContext(TodoContext);

  console.log(todoContext);

  return (
    <div>
      {todoContext.todos.map((todo) => (
        <TodoItem key={todo.id} todo={todo.title} />
      ))}
    </div>
  );
};

export default TodosList;

最后,这是我收到的错误。

TypeError: Cannot read property 'todos' of undefined
TodosList
C:/Users/Stacey/repos/simple-todo-app/src/components/TodosList.js:11
   8 |  console.log(todoContext);
   9 | 
  10 |  return (
> 11 |    <div>
     | ^  12 |      {todoContext.todos.map((todo) => (
  13 |        <TodoItem key={todo.id} todo={todo.title} />
  14 |      ))}

您正在导入 TodoContext 作为默认导入,但它必须是命名导入。

TodosList.js 中的变化:

import TodoContext from "../context/TodoContext";

至:

import { TodoContext } from "../context/TodoContext";

它会起作用