简体   繁体   English

如何使用 React 钩子将我的 Todo 组件数据传递到我的 Todolist 组件中?

[英]How can I pass my Todo component Data into my Todolist component using React hooks?

Here is a link https://codesandbox.io/s/fast-architecture-45u4m?file=/src/Todo.js这是一个链接https://codesandbox.io/s/fast-architecture-45u4m?file=/src/Todo.js

I added comments showing which code I am trying to move into a separate component.我添加了注释,显示我试图将哪些代码移到单独的组件中。

So I have this todo app and the original code has all of my functions and logic in one component called TodoList.js所以我有这个 todo 应用程序,原始代码在一个名为 TodoList.js 的组件中包含我的所有功能和逻辑

I'm trying to refactor my code, so that all the logic for the todo is in a separate component called Todo.js我正在尝试重构我的代码,以便 todo 的所有逻辑都在一个名为 Todo.js 的单独组件中

Here is what the code looks like这是代码的样子

 <>
      {todos.map(todo => (
        <div className='todo-row'>
          <div
            key={todo.id}
            className={todo.isComplete ? 'complete' : ''}
            key={todo.id}
            onClick={() => completeTodo(todo.id)}
          >
            {todo.text}
          </div>
          <FaWindowClose onClick={() => removeTodo(todo.id)} />
        </div>
      ))}
    </>

So I have this TodoList.js component with all of my state and functions, but when I tried to remove my todo code, I can't seem to figure out how to refactor it, so that the same data still gets passed in and I am able to use all of my functions again所以我有这个 TodoList.js 组件和我所有的状态和函数,但是当我试图删除我的 todo 代码时,我似乎无法弄清楚如何重构它,所以仍然传递相同的数据,我能够再次使用我的所有功能

      function TodoList() {
        const [todos, setTodos] = useState([]);

        const addTodo = todo => {
          if (!todo.text || /^\s*$/.test(todo.text)) {
            return;
          }

          const newTodos = [todo, ...todos];

          setTodos(newTodos);
          console.log(newTodos);
        };

        const removeTodo = id => {
          const removedArr = [...todos].filter(todoId => todoId.id !== id);

          setTodos(removedArr);
        };

        const completeTodo = id => {
          let updatedTodos = todos.map(todo => {
            if (todo.id === id) {
              todo.isComplete = !todo.isComplete;
            }
            return todo;
          });
          setTodos(updatedTodos);
        };

        return (
          <>
            <TodoForm onSubmit={addTodo} />
            <Todo />
          </>
        );
      }

      export default TodoList;

Originally, I replaced the component <Todo /> with the code I showed above in the first block.最初,我用上面第一个块中显示的代码替换了组件<Todo /> But now I wanna move all of that code into it's own component called Todo.js and then pass it in from there, but I'm running into errors because I have all my functions and state logic inside of the TodoList.js component但是现在我想将所有这些代码移动到它自己的名为 Todo.js 的组件中,然后从那里传入它,但是我遇到了错误,因为我在 TodoList.js 组件中拥有我的所有函数和状态逻辑

You can pass data and required functions to Todo component through props from TodoList component and Todo component should represent only on Todo item as per name so map should stay in TodoList component so after changes您可以通过TodoList组件中的 props 将数据和所需的函数传递给Todo组件,并且 Todo 组件应该按照名称仅代表 Todo 项,因此地图应保留在 TodoList 组件中,以便在更改后

TodoList.js TodoList.js

  function TodoList() {
    const [todos, setTodos] = useState([]);

    const addTodo = todo => {
      if (!todo.text || /^\s*$/.test(todo.text)) {
        return;
      }

      const newTodos = [todo, ...todos];

      setTodos(newTodos);
      console.log(newTodos);
    };

    const removeTodo = id => {
      const removedArr = [...todos].filter(todoId => todoId.id !== id);

      setTodos(removedArr);
    };

    const completeTodo = id => {
      let updatedTodos = todos.map(todo => {
        if (todo.id === id) {
          todo.isComplete = !todo.isComplete;
        }
        return todo;
      });
      setTodos(updatedTodos);
    };

    return (
      <>
        <TodoForm onSubmit={addTodo} />
        {
             todos.map(todo => <Todo to do = {todo} removeTodo={removeTodo} completeTodo={completeTodo}/>)
        }
      </>
    );
  }

  export default TodoList;

And Todo.js和 Todo.js

const {todo} = props;
return (
    <div className='todo-row'>
      <div
        key={todo.id}
        className={todo.isComplete ? 'complete' : ''}
        key={todo.id}
        onClick={() => props.completeTodo(todo.id)}
      >
        {todo.text}
      </div>
      <FaWindowClose onClick={() => props.removeTodo(todo.id)} />
    </div>
);
 

As per your sandbox .根据您的沙箱。 You just need to pass Props:你只需要传递道具:

Todo.js待办事项.js

// I want to move this code into this component
import React from "react";

import { FaWindowClose } from "react-icons/fa";

const Todo = ({ todos, completeTodo, removeTodo }) => {
  return todos.map((todo) => (
    <div className="todo-row">
      <div
        key={todo.id}
        className={todo.isComplete ? "complete" : ""}
        onClick={() => completeTodo(todo.id)}
      >
        {todo.text}
      </div>
      <FaWindowClose onClick={() => removeTodo(todo.id)} />
    </div>
  ));
};

export default Todo;


TodoList.js TodoList.js

import React, { useState } from "react";
import TodoForm from "./TodoForm";
import Todo from "./Todo";
import { FaWindowClose } from "react-icons/fa";

function TodoList({ onClick }) {
  const [todos, setTodos] = useState([]);

  const addTodo = (todo) => {
    if (!todo.text || /^\s*$/.test(todo.text)) {
      return;
    }

    const newTodos = [todo, ...todos];

    setTodos(newTodos);
    console.log(newTodos);
  };

  const removeTodo = (id) => {
    const removedArr = [...todos].filter((todoId) => todoId.id !== id);

    setTodos(removedArr);
  };

  const completeTodo = (id) => {
    let updatedTodos = todos.map((todo) => {
      if (todo.id === id) {
        todo.isComplete = !todo.isComplete;
      }
      return todo;
    });
    setTodos(updatedTodos);
  };

  return (
    <>
      <TodoForm onSubmit={addTodo} />
      {/* I want to move this code below into a new component called Todo.js */}
      <Todo todos={todos} completeTodo={completeTodo} removeTodo={removeTodo} />
    </>
  );
}

export default TodoList;

Here is the demo : https://codesandbox.io/s/nostalgic-silence-idm21?file=/src/TodoList.js:0-1039这是演示: https : //codesandbox.io/s/nostalgic-silence-idm21?file=/ src/TodoList.js: 0-1039

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用钩子在 React 中编辑我的待办事项? - How can I edit my todo items in React using hooks? 如何使用钩子在我的 React 应用程序中编辑待办事项? - How can I edit a todo in my react app using hooks? React:如何将“ const Todo =({todo,todoList,remove})=&gt; {”更改为“导出默认类Todo扩展React.Component {” - React: how change “const Todo = ({todo, todoList, remove}) => {” to “export default class Todo extends React.Component {” 如何将子组件中的{todo.id}发送到父组件的处理程序? - How can I send my {todo.id} in a child component to my parent component's handler? 我的 React 组件在 props 数据可用之前渲染,使用钩子 - My React component renders before the props data is available using hooks 我如何将反应钩子中的所有状态变量传递给我的子组件 - How do I pass all state variables inside react hooks to my child component 如何使用反应钩子将数据从子组件传递到父组件 - How to pass data from child to parent component using react hooks 如何防止我的功能组件使用 React 备忘录或 React 钩子重新渲染? - How can I prevent my functional component from re-rendering with React memo or React hooks? 如何在我的组件库中使用 React 钩子? - How do I use React hooks in my component library? 如何将数据传递给我的子组件? - How can I pass data to my child component?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM