无法读取未定义的属性ID,在地图函数(反应轨道)中发现错误

问题描述 投票:0回答:1

我正在尝试使我的提交按钮添加到项目列表中,我的轨道中的种子数据得到很好的渲染,但是当我单击提交时尝试添加新项目时,出现此错误Cannot read property id of undefined在地图功能上。发布请求正常运行,并且只有在刷新页面后,添加的项目才会呈现在页面上。任何帮助,将不胜感激!

class TodoList extends React.Component {


render() {
    const {todos} = this.props
    var todoItems = todos.map(title => <TodoItem key={title.id} title={title}/>)           //here
    return (
        <ListGroup className="my-2">
            <h2 className="text-center">Items</h2>
            {todoItems}
        </ListGroup>
    )
}

}导出默认的TodoList

class App extends React.Component {
constructor(props) {
    super(props)
    this.state = {
        todos: [],
        stuff: ''
    }
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.addNewTodo = this.addNewTodo.bind(this)
}

handleChange = event => {
    this.setState({
        stuff:event.target.value
    })
}

handleSubmit = event => {
    event.preventDefault()

    let body = JSON.stringify({todo: {item: this.state.stuff} })
    fetch('http://localhost:3000/api/v1/todos', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
             },
        body: body,
        })
        .then(response => {response.json()})
        .then(todo => {this.addNewTodo(todo)})
}

addNewTodo(todo){
this.setState({
  todos: this.state.todos.concat(todo)
    })
}
render() {
    return (
        <div className="container">
            <div className="row">
                <div className="col-10 mx-auto mt-4">
                    <h1 className="text-center">Todo List</h1>
                    <TodoInput 
                    stuff={this.state.stuff}
                    handleChange={this.handleChange}
                    handleSubmit={this.handleSubmit}
                    />
                    <TodoList 
                    todos={this.state.todos}
                    />
                </div>
            </div>
        </div>


    )
}

}

ruby-on-rails reactjs dictionary id
1个回答
0
投票

当您的组件首先渲染“待办事项”时,将没有任何值,它将是未定义的。尝试下面的代码

类TodoList扩展了React.Component {render(){const {todos} = this.props;

if (todos) {
  return (
    <ListGroup className="my-2">
      <h2 className="text-center">Items</h2>
      {todos.map(title => (
        <TodoItem key={title.id} title={title} />
      ))}
    </ListGroup>
  );
}
return "";   } }

导出默认的TodoList;

© www.soinside.com 2019 - 2024. All rights reserved.