繁体   English   中英

反应类型错误:this.state.List.map 不是 function

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM