React 中出现“无法读取未定义的属性‘map’”,这里出了什么问题?
2019-05-16
37
尝试理解 props,如果犯了一个愚蠢的错误,请原谅我。我尝试将所有数据传递到一个变量中,并将其传递到 props 中(使用 {item.text} 和 {item.key}),但是我的“.map”没有拾取任何内容,并且出现一堆错误,我的代码出了什么问题?
问题具体出在这块代码中
createList(list) {
return <li>{list.text}</li>
}
render() {
var entries = this.state.list
var finalEntries = entries.props.map(this.createList)
以下是完整代码
import React from "react";
import "./App.css";
import { isTemplateElement } from "@babel/types";
class TodoListt extends React.Component {
state = {};
constructor(props) {
super(props);
this.state = {
userInput: "",
list: [],
};
}
changeUserInput(input) {
this.setState({
userInput: input
})
}
addToList(input) {
let listArray = this.state.list;
listArray.push(input);
var newItem = {
text: listArray,
key: Date.now()
};
this.setState(prevState => {
return {
list: prevState.list.concat(newItem)
};
});
this.setState({
list: listArray
})
}
createList(list) {
return <li>{list.text}</li>
}
render() {
var entries = this.state.list
var finalEntries = entries.props.map(this.createList)
return (
<div className="to-do-list-main">
<input
onChange={(e) => this.changeUserInput(e.target.value)}
value={this.state.userInput}
type="text"
/>
<button onClick={() => this.addToList(this.state.userInput)}>Press me</button>
<ul>
{this.testingSetup()}
</ul>
</div>
);
}
}
export default TodoListt;
1个回答
您可以使用扩展运算符来添加到现有数组。只需在状态中向数组添加一个新对象,然后清除用户输入,为另一项做好准备。根据您的代码,这里有一个添加到状态列表的简单示例(我自己还没有运行过,所以只是检查语法错误等):
import React from "react";
import "./App.css";
import { isTemplateElement } from "@babel/types";
class TodoList extends React.Component {
state = {};
constructor(props) {
super(props);
this.state = {
userInput: "",
list: [],
};
}
changeUserInput(input) {
this.setState({
userInput: input
})
}
addToList() {
const { list, userInput } = this.state;
// Add item to state list using spread operator and clear input
this.setState({
list: [...list, {text:userInput, key: Date.now()}],
userInput: ""
});
}
render() {
return (
<div className="to-do-list-main">
<input
onChange={(e) => this.changeUserInput(e.target.value)}
value={this.state.userInput}
type="text"
/>
<button onClick={() => this.addToList()}>Press me</button>
<hr/>
{/* For each item in the list, render the contents */}
{this.state.list.map(item => (
<div key={item.key}>
<h3>{item.text}</h3>
<p>Time: {item.key}</p>
</div>
))}
</div>
);
}
}
export default TodoList;
Jayce444
2019-05-16