状态更改后从子组件重新渲染

时间:2019-10-16 14:31:11

标签: javascript reactjs

所以我想要的是,每当我单击任何列表项时,该项目都会被删除。我已经更改了状态,但不确定如何使用新状态重新呈现它。谁能让我知道该怎么做?

请不要介意我的错误,我是这个问题的新手,并建议我如何在需要时以更好的方式进行操作。

子组件

class TodoList extends Component {
  render() {
    return (
      <ul>
        {this.props.items.map(thing => (
          <List
            key={thing.id}
            item={thing}
            items={this.props.items}
            listid={thing.id}
          />
        ))}
      </ul>
    );
  }
}

class List extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  render() {
    return <li onClick={this.handleClick}>{this.props.item.item}</li>;
  }
  handleClick(event) {
    const items = this.props.items;
    items[this.props.listid] = {
      item: "<strike>" + event.target.value + "</strike>",
      id: this.props.listid
    };
    console.log(items);

    this.setState({
      items
    });
  }
}

1 个答案:

答案 0 :(得分:2)

您需要将待办事项状态保留在父组件中,并允许从内部组件状态更改。

例如:

App.js(此处,待办事项保持状态,并传递切换功能,待办事项作为对子组件的支持:

import React, { Component } from "react";
import TodoList from "./TodoList";

class App extends Component {
  state = {
    todos: [
      {
        id: 1,
        text: "todo 1",
        completed: false
      },
      {
        id: 2,
        text: "todo 2",
        completed: true
      },
      {
        id: 3,
        text: "todo 3",
        completed: true
      }
    ]
  };

  toggle = id => {
    const updatedTodos = this.state.todos.map(todo => {
      if (todo.id === id) {
        return {
          ...todo,
          completed: !todo.completed
        };
      }
      return todo;
    });

    this.setState({
      ...this.state,
      todos: updatedTodos
    });
  };

  render() {
    return <TodoList items={this.state.todos} toggle={this.toggle} />;
  }
}

export default App;

TodoList.js

import React, { Component } from "react";
import Todo from "./Todo";

class TodoList extends Component {
  render() {
    return (
      <ul>
        {this.props.items.map(todo => (
          <Todo key={todo.id} item={todo} toggle={this.props.toggle} />
        ))}
      </ul>
    );
  }
}

export default TodoList;

Todo.js(这里我们在handleClick时调用切换功能,并传递待办事项的ID)

import React, { Component } from "react";

class Todo extends Component {
  handleClick = id => {
    this.props.toggle(id);
  };

  render() {
    const { id, text, completed } = this.props.item;

    return (
      <li onClick={() => this.handleClick(id)}>
        {completed ? <strike>{text}</strike> : text}
      </li>
    );
  }
}

export default Todo;

这是codeandbox:

https://codesandbox.io/s/polished-cloud-hmdw0