反应-useContext返回未定义

时间:2020-10-19 21:26:25

标签: reactjs use-context

我试图使用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 |      ))}

1 个答案:

答案 0 :(得分:0)

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

TodosList.js中的更改:

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

收件人:

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

它将起作用