简体   繁体   中英

How to fix: React-Context - TypeError: Object is not iterable (cannot read property Symbol(Symbol.iterator))

I have tried some solutions that came by, on this link particularily...

I tried changing value inside my TodosContext.js file.. which didn't work, too.. One more thing that I have tried is to call useContext() function from another component, that didn't work neither..

Here's my code. App.js:

import React, { useState, useContext } from 'react';
import TodoList from './components/TodoList';
import NewTodo from './components/NewTodo';
import { TodosProvider, TodosContext } from './components/contextapi/TodosContext';

function App() {

  const [input, setInput] = useState('');
  const [todos, setTodos] = useContext(TodosContext);

  const _handleInput = (e) => {
    setInput(e.target.value)
  }

  const _todoAdd = (e) => {
    if (e.key === 'Enter') {
      setTodos(
        [...todos, { content: input, id: Date.now(), completed: false }]
      )
      setInput('')
    }
  }

  const _todoRemove = (id) => {
    const newTodos = todos.filter(todo => todo.id !== id)
    setTodos(newTodos)
  }

  return (
    <div>
      <header>
        <h3>To-Do Manager | Context API</h3>
      </header>
      <TodosProvider>
        <NewTodo newTodo={_todoAdd} handleInput={_handleInput} newVal={input} />
        <TodoList todos={todos} />
      </TodosProvider>
    </div>
  );
}

export default App;

TodosContext.js:

import React, { useState, createContext } from 'react';

export const TodosContext = createContext()

export const TodosProvider = ({ children }) => {
    const [todos, setTodos] = useState([]);
    return (
        <TodosContext.Provider value={[todos, setTodos]}>{children}</TodosContext.Provider>
    )
}

TodoList.js:

import React, { useContext } from 'react';
import Todo from './Todo';
import RemoveTodoFromList from './RemoveTodoFromList';
import { TodosContext } from './contextapi/TodosContext'

function TodoList() {

    const [todos, setTodos] = useContext(TodosContext);

    return (
        <div>
            {todos.map(todo => (
                <div>
                    <Todo key={todo.id} todo={todo} />
                </div>
            ))}
        </div>
    )
}

export default TodoList

I'm really struggling with this one, I spent whole day figuring out what went wrong.. Thanks!

We fixed it inside the comments.

createContext needs an object as parameter that defines your context. In your case it should be export const TodosContext = createContext([[],() => {}]) . So the application knows the first element of the tuple is an array and so iterable.

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