![](/img/trans.png)
[英]TypeError: undefined is not a function (evaluating 'this.state.list.map')
[英]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;
您好,在運行此程序時,createProject 將作為道具傳遞給另一個 class,該 class 使用某些參數調用 createProject。 但是,在嘗試渲染時,它會返回此錯誤。 類型錯誤:this.state.projectList.map 不是 function。 關於如何解決它的任何建議?
push
返回數組的新長度,它不返回數組。 所以這段代碼用一個數字替換了數組:
this.setState({
projectList: this.state.projectList.push( // <============
{
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}
)
});
數字沒有map
方法。 :-)
您可能想要這樣做,它會創建一個新數組,其中添加了新項目:
this.setState({
projectList: [...this.state.projectList, {
title : title,
description : desc,
language : langs,
length : len,
experience : exp
}]
});
您不能像這樣聲明 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.