地图未在 reactjs 中呈现 ui 元素 [英] map is not rendering the ui elements in reactjs
问题描述
当 todos 对象更新时,呈现
对象的最佳方法是什么?我试过通过它映射,但它没有返回任何错误.
代码:
从'react'导入React;const Todo = React.createClass({getInitialState() {返回 ({todos: []})},newTodo(e) {让今天=新日期();if (e.key === '回车') {控制台日志(this.state.todos)this.setState({todos: this.state.todos.concat({title: e.target.value, date: today})})}},delTodo(e) {},使成为() {返回 (<div className="panel panel-default"><div className="panel-heading">待办事项列表创建器</div><div className="panel-body"><input type="text" placeholder="输入待办事项名称" className="form-control" onKeyPress={this.newTodo}/>
<ul className="list-group">{this.state.todos.map((td, index) => {<li key={index} className="list-group-item"><strong>{td.name}</strong><br/>{日期}})}
);}});导出默认 Todo
map
正文中没有返回任何内容,如果不返回任何内容,则使用 map
默认返回 undefined
.
使用这个:
{this.state.todos.map((td, index) => {return - <strong>{td.name}</strong><br/>{td.date.toDateString()}
})}
或者您也可以这样编写,而无需使用 {}
:
{this.state.todos.map((td, index) => (<li key={index} className="list-group-item"><strong>{td.name}</strong><br/>{td.date.toDateString()}))}
注意:
我们不能直接在 jsx
内部渲染任何 object/array
,因为 date 是一个对象,所以你需要把它转换成 string
通过使用 toDateString()
或任何其他 date
方法.
检查工作待办事项示例:
const Todo = React.createClass({getInitialState() {返回 ({todos: []})},newTodo(e) {让今天=新日期();if (e.key === '回车') {this.setState({todos: this.state.todos.concat({title: e.target.value, date: today})})}},delTodo(索引){让 todos = this.state.todos.slice();todos.splice(index, 1);this.setState({todos})},使成为() {返回 (<div className="panel panel-default"><div className="panel-heading">待办事项列表创建器</div><div className="panel-body"><input type="text" placeholder="输入待办事项名称" className="form-control" onKeyPress={this.newTodo}/>
<ul className="list-group">{this.state.todos.map((td, index) => {return
);}});ReactDOM.render(
<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'/>