[英]React TypeError: this.state.List.map is not a function
import React, { Component } from "react"; import Project from "./components/Project.js" import Form from "./Form.js"; class App extends Component { constructor(props) { super(props); this.state = { projectList: [], myProjects: [], userList: [], }; this.createProject = this.createProject.bind(this); } createProject(title, desc, langs, len, exp) { this.setState({ projectList: this.state.projectList.push( { title: title, description: desc, language: langs, length: len, experience: exp } ) }); } deleteProject(title) { const projects = this.state.projectList.filter( p => p.title;== title ). this;setState({projects}). } render() { return( <div> <Form createProject = {this.createProject} /> {this.state.projectList.map((params) => <Project {..;params}/>)} </div> ); } } export default App;
Hello, when running this, createProject gets passed as a prop to another class, which calls createProject with certain parameters.您好,在运行此程序时,createProject 将作为道具传递给另一个 class,该 class 使用某些参数调用 createProject。 However, upon trying to render, it returns this error.
但是,在尝试渲染时,它会返回此错误。 TypeError: this.state.projectList.map is not a function.
类型错误:this.state.projectList.map 不是 function。 Any advice on how to fix it?
关于如何解决它的任何建议?
push
returns the new length of the array, it doesn't return the array. push
返回数组的新长度,它不返回数组。 So this code is replacing the array with a number:所以这段代码用一个数字替换了数组:
this.setState({
projectList: this.state.projectList.push( // <============
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
)
});
Numbers don't have a map
method.数字没有
map
方法。 :-) :-)
You probably wanted to do this, which creates a new array with the new item added to it:您可能想要这样做,它会创建一个新数组,其中添加了新项目:
this.setState({
projectList: [...this.state.projectList, {
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}]
});
You cannot declare state like this, you can do something like:您不能像这样声明 state,您可以执行以下操作:
this.setState({
projectList: [...this.state.projectList, (
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
)]
});
Hi Adam,
For the current problem below snippet would solve this issue
this.setState({
projectList: [...this.state.projectList,
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
]
});
For better understanding refer below link:
https://www.robinwieruch.de/react-state-array-add-update-remove
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.