D
D
depstor2020-04-20 21:22:51
React
depstor, 2020-04-20 21:22:51

It throws an error when iterating, why?

Good afternoon, there are 3 components, why does the error fall??

component 1

import React, { useState } from 'react';
import { Form, Input, Button } from 'antd';
import style from '../../Index.module.scss';
import TodoList from '../TodoList/TodoList';


const App = () => {

const [todos, setTodos] = useState([]);

const onFinish = values => {
  const newTodoItem = {title: values.todoTitle, complete: false}
  const newTodos = [...todos, newTodoItem]
  setTodos(newTodos)
}

  return (
      <>
      <h1 className={style.title}>To-Do</h1>
    <Form
      name="basic"
      onFinish={onFinish}
      style={{ width: 200 }}
    >
      <Form.Item name="todoTitle">
        <Input />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit">
          Add
        </Button>
      </Form.Item>
    </Form>
    <TodoList/>
    </>
  );
};

export default App;


component 2
import React from 'react';
import { Checkbox } from 'antd';


const TodoItem = ({ item, index, onChange }) => {
    onChange = (event, currentIndex, todos, setTodos) => { 
        const value = event.target.checked
            const newItems = todos.map((res, index) => ({
                ...res,
                complete: currentIndex === index ? value : res.complete
            }));
            setTodos(newItems);
        }
return (
<h3 key={index}>
    <Checkbox checked={item.complete} onChange={(e) => onChange(e, index)} />
    { item.title }
</h3>
)

}
export default TodoItem ;


component 3

import React from 'react';
import TodoItem  from '../TodoItem/TodoItem';


const TodoList = ({ todos, onChange }) => {
    return (
      todos.map((res, index) => 
      <TodoItem 
      key={index} 
      item={res} 
      index={index} 
      onChange={onChange}/>)
    )
  }
export default TodoList;


here is the error

TypeError: Cannot read property 'map' of undefined

3 |
4 |
5 | const TodoList = ({ todos, onChange }) => {
> 6 | return (
7 | todos.map((res, index) =>
8 | 9 | key={index}

what is the reason ??? how to solve this and not allow it anymore ?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Abr_ya, 2020-04-20
@depstor

Cannot read property 'map' of undefined
todos does not come
Before mapping, it would be good to check that:
- this is an array,
- an array of non-zero length.
<TodoList/>
And where is the transfer of props when called?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question