Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

javascript - "TypeError: props.todos.map is not a function" can't figure out what the cause is?

I am trying to create my first Todo list with React.js. I am trying to change the state from

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

To:

const [todos, setTodos] = useState({
    todo: [],
    isCompleted: false,
  })

Just to try and add in a isCompleted state. However, when I change it, I get an error when running my application from a previously working map. The error is in the title.

Could somebody tell me what is wrong?

Code:

TodosApp.js

import React, { useState } from "react"
import Todos from "./Todos"

const TodoApp = () => {
  const [todos, setTodos] = useState({
    todo: [],
    isCompleted: false,
  })
  const [input, setInput] = useState("")

  const handleCurrentInput = (e) => {
    setInput(e.target.value)
  }
  const handleSubmit = (e) => {
    e.preventDefault()
    console.log(input)
    setInput("")
    setTodos({
      ...todos,
      task: input,
      isCompleted: false,
    })
  }

  const handleDelete = ({ index }) => {
    const newTodos = [...todos]
    newTodos.splice(index, 1)
    setTodos(newTodos)
  }

  return (
    <div id="todoForm">
      <div class="container">
        <div class="todo_form">
          <div class="todo_input">
            <form onSubmit={handleSubmit}>
              <input
                type="text"
                id="input_todo"
                onChange={handleCurrentInput}
                value={input}
              />
            </form>
            <Todos todos={todos} handleDelete={handleDelete} />
          </div>
        </div>
      </div>
    </div>
  )
}

export default TodoApp

Todos.js

import React, { useState } from "react"

const Todos = (props) => {
  return (
    <ul>
      {props.todos.map((todo, index) => {
        return (
          <li key={todo}>
            {todo}
            <button onClick={() => props.handleDelete({ index })}>
              Delete
            </button>
          </li>
        )
      })}
    </ul>
  )
}

export default Todos


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to focus on each todo item including 2 props task, isCompleted instead of isCompleted of todos.

const [todos, setTodos] = useState([]);
var newTodo = {
                task: 'React JS',
                isCompleted: false
             };
setTodos([...todos, newTodo]);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...