簡體   English   中英

為什么在 state 更改后 React 不重新渲染頁面?

[英]Why isn't React re-rendering the page after the state is changed?

所以我正在使用 React.js 開發一個基本的 Todo 應用程序,我想知道為什么一旦 state 更改后 todo 組件不會自動重新渲染(state 包含待辦事項列表 - 所以添加新的 todo 會更新這個數組) ? 它應該重新渲染 Header 和頁面的 Todo 組件,其中更新的 todo 數組作為 props 傳入。 這是我的代碼:

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>
      )
  }
}

您沒有正確更新 state。

您需要復制this.state.todos ,在復制的數組中添加新的 todo 然后調用this.setState

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

注意this.setState是一個 function

您正在錯誤地更新 state,

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

這是正確的語法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM