React Function组件-跟随父组件状态

时间:2019-08-04 11:49:08

标签: reactjs

我是新来的人,我正在尝试组件功能样式。 我有简单的待办事项清单。我想使用style属性从列表中删除待办事项。在Chrome调试模式下,我没有看到对复选框更改的立即反应,也没有删除项目...这对我来说很明显,这是我如何管理组件状态的问题。我希望得到一些指导。

App.js

update s
    set s.Date = fd.Date,
        s.Name = fd.Name,
        . . .
from SecondDates s join
     (select fd.*,
             row_number() over (partition by location order by date desc) as seqnum
     ) fd
     on f.Location = s.Location
where seqnum = 1;

Todos.js

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

import './App.css'

const App = () => {
    const [todos, setTodos] = useState(
        [
            {id: 1, title: 'Take out the trash', completed: false},
            {id: 2, title: 'Dinner with wife', completed: false},
            {id: 3, title: 'Meeting boss', completed: false}
        ]
    );

    const markComplete = id => {
        console.log((new Date()).toString());

        todos.map(todo => {
            if (todo.id === id) {
                todo.completed = ! todo.completed;
            }
            return todo;
        });
        setTodos(todos);
    };

    return (
        <div className="App">
            <Todos todos={todos} markComplete={markComplete}/>
        </div>
    );
};

export default App;

TodoItem.js

import React from "react";
import TodoItem from "./TodoItem";

const Todos = ({todos, markComplete}) => {
    return (
        todos.map(todo => (
            <TodoItem key={todo.id} todoItem={todo} markComplete={markComplete} />
        ))
    );
};

export default Todos;

我希望这个getStyle()会遵循状态...以某种方式...

2 个答案:

答案 0 :(得分:2)

请勿更改状态。在markComplete函数中,您将直接对todos数组进行突变。像这样更改您的功能以避免突变

const markComplete = id => {
   console.log((new Date()).toString());
   let newTodos = todos.map(todo => {
       let newTodo = { ...todo };
       if (newTodo.id === id) {
           newTodo.completed = !newTodo.completed;
       }
       return newTodo;
    });
    setTodos(newTodos);
};

答案 1 :(得分:1)

Array.prototype.map()返回一个新的数组,您将其丢弃。您需要使用新数组,例如:

const markComplete = id => {
  ...
  setTodos(totos.map(...))