简体   繁体   English

请帮我找出为什么我的反应组件没有正确地在 jsx 中映射我的列表

[英]Please help me find out why my react component is not mapping my list in jsx correct

I am using handleChange event to set the task using setTask() then I am using handleSubmit event to push that same task into an array when I console log the task and the array length they are both correct so I know I am modifying the array, but its still not mapping correct in my Unordered List element:我正在使用 handleChange 事件使用 setTask() 设置任务,然后当我控制台记录任务和数组长度时,我使用 handleSubmit 事件将相同的任务推送到数组中,它们都是正确的,所以我知道我正在修改数组,但它在我的无序列表元素中仍然没有正确映射:

import React, { useState } from 'react';

const App = () => {
  const [task, setTask] = useState('');

  const myTaskList = [];

  const allTasks = myTaskList.map((eachTask) => {
    return <li key={eachTask.id}>{eachTask.text}</li>;
  });

  const handleChange = (e) => {
    setTask(e.target.value);
    console.log(task);
    return task;
  };

  const handleSubmit = (e) => {
    myTaskList.push({
      id: Math.floor(Math.random() * 10000),
      text: task,
    });
    setTask('');
    console.log(myTaskList.length);
  };

  return (
    <div className="todo-app">
      <center>
        <h1>MONO To Do APP</h1>
        <p>Track your progress , add tasks, then mark complete when done</p>
        <div className="space"></div>
        <form onSubmit={handleSubmit}>
          <label>Enter your next task:</label>
          <br />
          <input
            onChange={handleChange}
            value={task}
            type="text"
            name="task"
            placeholder="enter a task to track your progress..."
          />
          <br />
          <button type="submit">Add</button>
        </form>
        <div className="space"></div>
        <div className="task-list">
          <h2>Your Active Tasks List</h2>
          <ul>{allTasks.length > 0 ? allTasks : <li>no tasks found</li>}</ul>
        </div>
      </center>
    </div>
  );
};
export default App;

You should put myTaskList in a state to make the UI update when it changes.您应该将myTaskList放在 state 中,以便在 UI 更改时进行更新。

const [myTaskList, setMyTaskList] = useState([])


 const handleSubmit = (e) => {
   setMyTaskList(prev => {
     const myTaskList = [...prev]
     myTaskList.push({
      id: Math.floor(Math.random() * 10000),
      text: task,
     });
     return myTaskList
   })
   
  setTask('');
};

You need to create a state using useState so that when you update the state then React will re-render the component您需要使用useState创建一个 state ,这样当您更新 state 时,React 将重新渲染组件

const [myTaskList, setMyTaskList] = useState( [] );

CODESANDBOX LINK CODESANDBOX 链接

Since you are using form here so you also have to preventDefault由于您在这里使用form ,因此您还必须preventDefault

  const handleSubmit = ( e ) => {
    e.preventDefault();  // CHANGE
    setMyTaskList( ( oldTask ) => {   // CHANGE
      return [
        ...oldTask,
        {
          id: Math.floor( Math.random() * 10000 ),
          text: task,
        }
      ];
    } );
    setTask( '' );
    console.log( myTaskList.length );
  };

You can also do as:你也可以这样做:

  const handleSubmit = (e) => {
    e.preventDefault();
    setMyTaskList([  // CHANGE
      ...myTaskList,
      {
        id: Math.floor(Math.random() * 10000),
        text: task
      }
    ]);
    setTask("");
    console.log(myTaskList.length);
  };

Several issues in your code.您的代码中有几个问题。

  1. you did not use useState in your taskList您没有在 taskList 中使用 useState
  2. You did not call preventDefault()您没有调用 preventDefault()

Heres mine:这是我的:

import React, { useState } from 'react';

const App = () => {
const [task, setTask] = useState('');
const [myTaskList, setMyTaskList] = useState([])

// const allTasks = myTaskList.map((eachTask) => {
//   return <li key={eachTask.id}>{eachTask.text}</li>;
// });

const handleChange = (e) => {
  setTask(e.target.value);
  console.log(task);
  return task;
};

const handleSubmit = (e) => {
  e.preventDefault()
  // setMyTaskList.push({
  //   id: Math.floor(Math.random() * 10000),
  //   text: task,
  // });
  setMyTaskList(arry=>[...arry, {
    id: Math.floor(Math.random() * 10000),
    text: task,
  }])
  setTask('');
  console.log(myTaskList.length);
};

return (
  <div className="todo-app">
    <center>
      <h1>MONO To Do APP</h1>
      <p>Track your progress , add tasks, then mark complete when done</p>
      <div className="space"></div>
      <form onSubmit={handleSubmit}>
        <label>Enter your next task:</label>
        <br />
        <input
          onChange={handleChange}
          value={task}
          type="text"
          name="task"
          placeholder="enter a task to track your progress..."
        />
        <br />
        <button type="submit">Add</button>
      </form>
      <div className="space"></div>
      <div className="task-list">
        <h2>Your Active Tasks List</h2>
        <ul>{myTaskList.length > 0 ? myTaskList.map((eachTask) => {
  return <li key={eachTask.id}>{eachTask.text}</li>;
}) : <li>no tasks found</li>}</ul>
      </div>
    </center>
  </div>
);
};
export default App;

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

相关问题 我无法删除使用 react 创建的待办事项列表中的项目,请帮助我解决代码中的错误 - I am not able to delete items in my todo list made with react, please help me with error in my code 我的代码有什么问题? 任何人都可以帮助我吗 - What is the problem in my code? Can any please help me out 为什么我的 React 组件将我的 JSX 呈现为文本而不是 HTML? - Why is my React component rendering my JSX as text rather than HTML? 为什么对象数组的映射在我的 react 表组件中不起作用? - Why mapping of array of objects not working in my table component of react? 为什么我的React / JSX if语句仍在执行? - Why is my React/JSX if statement still executing? 为什么我的 React 组件图标会以 typeof 对象的形式出现? - Why is my React component icon coming out as a typeof object? 我的 React 组件正在重新渲染,不知道为什么 - My React component is re-rendering, cannot figure out why 你能帮我处理 JSX 和 React 吗? - Can you help me with JSX and React? 我的组件没有显示 React 映射 - my component isn't shown with React mapping React/MERN 堆栈应用程序在读取 state 属性时抛出错误,但它们仍然呈现? 请帮我调试我的第一个小游戏 - React/MERN stack app is throwing errors on state property read, but they are still rendered? Please help me with debugging my first small game
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM