Javascript 为什么不是';是否在状态更改后重新呈现页面?
因此,我正在使用React.js开发一个基本的Todo应用程序,我想知道为什么Todo组件在状态更改后不会自动重新呈现(状态包含Todo列表-因此添加一个新的Todo会更新此数组)?它应该使用作为道具传入的更新Todo数组重新呈现页面的标题和Todo组件。这是我的密码:Javascript 为什么不是';是否在状态更改后重新呈现页面?,javascript,reactjs,Javascript,Reactjs,因此,我正在使用React.js开发一个基本的Todo应用程序,我想知道为什么Todo组件在状态更改后不会自动重新呈现(状态包含Todo列表-因此添加一个新的Todo会更新此数组)?它应该使用作为道具传入的更新Todo数组重新呈现页面的标题和Todo组件。这是我的密码: import React from 'react'; import './App.css'; class Header extends React.Component { render() { let numTod
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>
)
}
}
从“React”导入React;
导入“/App.css”;
类头扩展了React.Component{
render(){
让numTodos=this.props.todos.length;
返回{您有${numTodos}todos`}
}
}
类Todos扩展了React.Component{
render(){
返回(
{
this.props.todos.map((todo,index)=>{
返回()
})
}
)
}
}
类Todo扩展了React.Component{
render(){
return{this.props.todo}
}
}
类形式扩展了React.Component{
建造师(道具){
超级(道具);
this.addnewTodo=this.addnewTodo.bind(this);
}
addnewTodo=()=>{
让inputBox=document.getElementById(“输入框”);
如果(inputBox.value==''){
返回;
}
this.props.handledd(inputBox.value);
}
render(){
返回(
添加
)
}
}
类应用程序扩展了React.Component{
建造师(道具){
超级(道具);
this.state={todos:['task 1','task 2','task 3']}
this.handleNewTodo=this.handleNewTodo.bind(this);
}
handleNewTodo(todo){
让tempList=this.state.todos;
圣殿骑士推(todo);
this.setState={todos:templast};
}
render(){
返回(
)
}
}
您没有正确更新状态
您需要复制this.state.todo
,在复制的数组中添加新的todo,然后调用this.setState
函数
handleNewTodo(todo) {
let tempList = [...this.state.todos];
tempList.push(todo);
this.setState({ todos: tempList });
}
请注意,
this.setState
是一个函数您正在错误地更新状态
handleNewTodo(todo) {
let tempList = [...this.state.todos];
tempList.push(todo);
this.setState({ todos: tempList });
}
这是正确的语法