当待办对象更新时,渲染
对象的最佳方式是什么?我试过通过它进行映射,但它没有返回任何错误。
代码:
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
。
使用这个:
<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>
注意:
我们不能直接在 jsx
中渲染任何 object/array
,因为 date 是一个对象所以你需要把它转换成 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);
关于reactjs - map 没有在 reactjs 中渲染 ui 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44008700/