我试图在React中映射和对象,并且一直收到以下错误:"TypeError: Cannot read property ' map‘of undefined“
我的预期结果
任务-1任务-2任务-3任务-4
代码
import React, { Component } from 'react';
class MapEx extends Component {
constructor(props) {
super(props);
this.state = {
tasks: {
'task-1': { id: 'task-1', content: 'clean house' },
'task-2': { id: 'task-2', content: 'walk dog' },
'task-3': { id: 'task-3', content: 'Do pushups' },
'task-4': { id: 'task-4', content: 'have a drink' }
}
};
}
render() {
const tasks = this.state.tasks
console.log(tasks)
return (
<div>
<h1>Hello</h1>
<p> {this.tasks.map((task) =>
task.id)}</p>
</div>
);
}
}
export default MapEx;发布于 2020-04-16 23:24:39
两个问题:
你引用的是this.tasks而不是this.state.tasks.
map。尝试如下所示:
return (
<div>
<h1>Hello</h1>
{Object.values(this.state.tasks).map(task => <p>{task.id}</p>)}
</div>
);发布于 2020-04-16 23:23:42
map只能在数组上使用。首先,将您的数据转换为数组DS,并按以下步骤进行操作。
import React, { Component } from 'react';
class MapEx extends Component {
constructor(props) {
super(props);
this.state = {
tasks: {
'task-1': { id: 'task-1', content: 'clean house' },
'task-2': { id: 'task-2', content: 'walk dog' },
'task-3': { id: 'task-3', content: 'Do pushups' },
'task-4': { id: 'task-4', content: 'have a drink' }
}
};
}
render() {
const tasks = this.state.tasks
console.log(tasks)
return (
<div>
<h1>Hello</h1>
{Object.values(tasks).map(task => (<p>{task.id}</p>))}
</div>
);
}
}
export default MapEx;发布于 2020-04-16 23:43:35
你可以这样做:
import React, { Component } from 'react';
class MapEx extends Component {
constructor(props) {
super(props);
this.state = {
tasks: {
'task-1': { id: 'task-1', content: 'clean house' },
'task-2': { id: 'task-2', content: 'walk dog' },
'task-3': { id: 'task-3', content: 'Do pushups' },
'task-4': { id: 'task-4', content: 'have a drink' }
}
};
}
render() {
const {tasks} = this.state
console.log(tasks)
return (
<div>
<h1>My tasks</h1>
{!!tasks ? Object.values(tasks).map(task => (<p>{task.id}</p>)) : null}
</div>
);
}
}
export default MapEx;https://stackoverflow.com/questions/61253893
复制相似问题