提问者:小点点

为什么React不在状态更改后重新呈现页面?


所以我正在使用react.js开发一个基本的Todo应用程序,我想知道为什么Todo组件不能在状态改变后自动重新呈现(状态包含Todo列表--所以添加一个新的Todo会更新这个数组)? 它应该重新呈现页面的头和Todo组件,并将更新后的Todo数组作为道具传入。 下面是我的代码:

import React from 'react';
import './App.css';

class Header extends React.Component {
  render() {
    let numTodos = this.props.todos.length;
    return <h1>{`You have ${numTodos} todos`}</h1>
  }
}

class Todos extends React.Component {
  render() {
    return (
    <ul>
      {
    this.props.todos.map((todo, index) => {
      return (<Todo index={index} todo={todo} />)
    })
    }
    </ul>
    )
  }
}

class Todo extends React.Component {
  render() {
    return <li key={this.props.index}>{this.props.todo}</li>
  }
}

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.addnewTodo = this.addnewTodo.bind(this);
  }

  addnewTodo = () => {
    let inputBox = document.getElementById("input-box");
    if (inputBox.value === '') {
      return;
    }
    this.props.handleAdd(inputBox.value);
  }

  render() {
    return (
      <div>
        <input id="input-box" type="text"></input>
        <button type="submit" onClick={this.addnewTodo}>Add</button>
      </div>
    )
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { todos: ['task 1', 'task 2', 'task 3']}
    this.handleNewTodo = this.handleNewTodo.bind(this);
  }

  handleNewTodo(todo) {
    let tempList = this.state.todos;
    tempList.push(todo);
    this.setState = { todos: tempList };
  }

  render() {
    return (
      <div>
      <Header todos={this.state.todos} />
      <Todos todos={this.state.todos} /> 
      <Form todos={this.state.todos} handleAdd={this.handleNewTodo} />
      </div>
      )
  }
}

共1个答案

匿名用户

您没有正确更新状态。 您需要制作this.state.Todos的副本,在其中添加新的todo,然后调用this.setstate

handleNewTodo(todo) {
    let tempList = [...this.state.todos];
    tempList.push(todo);
    this.setState = { todos: tempList };
}