更改后组件不会重新呈现

时间:2020-09-08 17:54:24

标签: javascript reactjs frontend

我正在使用三个组件来构建基本的待办应用程序: CreateTodo TodoList TodoItem 。但是,无论何时键入新任务并单击按钮, TodoList 都不会重新渲染,直到我对文本输入执行某种更改。此外,将任务设置为完成后,除非刷新页面,否则 TodoItem 不会重新呈现新样式。我是Reactjs的新手,因此对这些bug的任何评论都将非常有帮助。这些是组件:

CreateTodo:

app.php

TodoList:

//install the package and add it in composer file
 composer require laravel/cashier

//add your cashier class in 'providers' array in app.php
 Laravel\Cashier\CashierServiceProvider::class,

//add alias in 'aliases' array in app.php
'Cashier' => Laravel\Cashier\CashierServiceProvider::class,

//will add several columns to users table & create a new subscriptions table
 php artisan migrate

TodoItem:

function CreateTodo() {
    
    const [todo, setTodo] = useState({title: "", done: false});
    const [todoArr, setTodoArr] = useState([]);

    const onChange = (event) => {
        let {value} = event.target;
        let obj = {};
        obj["title"] = value;
        obj["done"] = false;
        setTodo(obj);
    }

    const createTodo = (event) => {
        const {name} = event.target;
        if(event.key === "Enter" || name === "addTodo"){
            if(todo.title !== ""){
                todoArr.unshift(todo);
                localStorage.setItem('todos', JSON.stringify(todoArr));
            }else{
                swal("Oops", "Please write todo first", "error");
            }
        }
    }

    const completeTodo = (i) => {
        if(todoArr[i]["done"] !== true){
            todoArr[i]["done"] = true;
            localStorage.setItem("todos", JSON.stringify(todoArr));
            setTodoArr(todoArr);
            swal("Good job!", "Todo Completed", "success");
        }
    }

    return (
        <>
            <div className = "card">
                <div className = "card-header">
                    
                </div>
                <div className = "card-body">
                    <h5 className = "card-title">Add a new Todo</h5>
                    <form className = 'form-inline justify-content-center'>
                        <input type = 'text' className = 'form-control' placeholder = 'New Todo' onKeyPress = {createTodo} onChange = {onChange} value = {todo.title}/>
                        <button type = "button" name = "addTodo" className = "btn btn-primary" onClick = {createTodo}>Add Todo</button>
                    </form>   
                </div>
            </div>
            <TodoList todoArr = {todoArr} completeTodo = {completeTodo} />
        </>
    );
}

0 个答案:

没有答案