render更新待办事项中的对象的最佳方法是什么?我尝试通过它进行映射,但是它没有返回任何错误。
render
码:
import React from 'react'; const Todo = React.createClass({ getInitialState() { return ({todos: []}) }, newTodo(e) { let today = new Date(); if (e.key === 'Enter') { console.log(this.state.todos) this.setState({ todos: this.state.todos.concat({title: e.target.value, date: today}) }) } }, delTodo(e) {}, render() { return ( <div className="panel panel-default"> <div className="panel-heading">Todo List Creator</div> <div className="panel-body"> <input type="text" placeholder="enter todo name" className="form-control" onKeyPress={this.newTodo}/> </div> <ul className="list-group"> {this.state.todos.map((td, index) => { <li key={index} className="list-group-item"> <strong>{td.name}</strong><br/> {td.date} </li> })} </ul> </div> ); } }); export default Todo
您不会在map体内返回任何内容,map如果您不返回任何内容,则undefined默认情况下它将返回。
map
undefined
用这个:
<ul className="list-group"> {this.state.todos.map((td, index) => { return <li key={index} className="list-group-item"> <strong>{td.name}</strong> <br/> {td.date.toDateString()} </li> }) } </ul>
或者,您也可以这样编写它,而无需使用{}:
{}
<ul className="list-group"> {this.state.todos.map((td, index) => ( <li key={index} className="list-group-item"> <strong>{td.name}</strong> <br/> {td.date.toDateString()} </li> )) } </ul>
注意:
我们不能直接渲染任何object/array内部jsx,因为date是一个对象,因此您需要string使用toDateString()或任何其他date方法将其转换为。
object/array
jsx
string
toDateString()
date
查看待办事项示例:
const Todo = React.createClass({ getInitialState() { return ({todos: []}) }, newTodo(e) { let today = new Date(); if (e.key === 'Enter') { this.setState({ todos: this.state.todos.concat({title: e.target.value, date: today}) }) } }, delTodo(index) { let todos = this.state.todos.slice(); todos.splice(index, 1); this.setState({todos}) }, render() { return ( <div className="panel panel-default"> <div className="panel-heading">Todo List Creator</div> <div className="panel-body"> <input type="text" placeholder="enter todo name" className="form-control" onKeyPress={this.newTodo}/> </div> <ul className="list-group"> {this.state.todos.map((td, index) => { return <li key={index} className="list-group-item"> <strong>{td.title}</strong> <button onClick={() => this.delTodo(index)}>delete</button> <br/> {td.date.toDateString()} </li> }) } </ul> </div> ); } }); ReactDOM.render(<Todo/>, document.getElementById('app')) <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id='app'/>
查看此代码段以了解map:
let a = [1,2,3,4,5,6]; let b = a.map(el => { if(el % 2) return el; }); console.log(b);