更新父组件的状态后,子组件中的道具不更新

props not updating in child component after parent component's state is updated

我正在开发一个 ToDo 应用程序,我传递了一个包含对象的任务数组,但是在将任务作为道具传递后,它永远不会在 ToDoList 中更新。 请帮助我,感谢您的帮助,并想知道其背后的逻辑。

App.js :- 这是所有代码都存在的入口文件

import { useState, useEffect } from 'react';
import './App.css';
import AddToDo from './components/addToDo';
import Filter from './components/Filter';
import ToDoList from './components/toDoList';

window.id = 0;

function App() {
    const [value, setvalue] = useState('');
    const [tasks, settasks] = useState([]);
    const handleChange = (e) => setvalue(e.target.value);
    const handleTasks = (val) => {
        tasks.push({ text: val, completed: false, id: window.id++ });
        settasks(tasks);
        localStorage.setItem('tasks', JSON.stringify(tasks));
    };

    return (
        <div className="row flex-center flex-middle flex">
            <div className="border border-primary padding-large margin-large no-responsive paper">
                <h3>Narries ToDo</h3>
                <AddToDo onChange={handleChange} value={value} onAdd={handleTasks} />
                <ToDoList tasks={tasks} />
                <Filter />
            </div>
        </div>
    );
}

export default App;

AddToDo 这是我们通过在 app.js

中更改状态来添加任务的地方
import React from 'react';

const AddToDO = (props) => {
    return (
        <div className="row">
            <div className="col padding-right-small">
                <input type="text" placeholder="New Todo" value={props.value} onChange={props.onChange} />
            </div>
            <div className="col padding-left-small">
                <button value="Add" className="paper-btn btn-small" onClick={() => props.onAdd(props.value)}>
                    Add
                </button>
            </div>
        </div>
    );
};

export default AddToDO;

ToDoList.js:- 这是应该更新任务道具的地方。

import React, { useState } from 'react';

const ToDoList = (props) => {
    return (
        <div className="child-borders">
            {props.tasks.map((task, id) => {
                return (
                    <div
                        className={
                            'padding-small margin-small ' +
                            (task.completed ? 'background-primary' : 'shadow shadow-hover')
                        }
                        key={id}
                    >
                        {task.text}
                    </div>
                );
            })}
        </div>
    );
};

export default ToDoList;

您已经改变了原始任务数组。每次更改值时,任务数组都会被覆盖。因此,您需要将任务数组更新为:

const handleTasks = (val) => {
  let customTask = { text: val, completed: false, id: window.id++ };
  settasks(tasks => [...tasks, customTask]);
  localStorage.setItem('tasks', JSON.stringify(tasks));
};

you should never directly mutate/change your state remove this line tasks.push({ text: val, completed: false, id: window.id++ }); in your ToDoList.js it should only be task and not task.text