猿问

反应 this.state.addroom.map 不是一个函数

所以我试图用一个按钮的按钮 onClick 生成一个 div,但我收到一个错误,阻止我这样做。


错误:TypeError: this.state.addroom.map is not a function


但是我看到,当我单击按钮时,它不会显示错误,但也不会生成带有按钮的 div。


这是我的代码:



import React, { Component } from 'react';

import Select, { components } from 'react-select';

import styles from '../styles/loginsignup.css'

import axios from 'axios'

import nextId from "react-id-generator";

export default class AccomodationInfo extends Component {


    constructor() {

        super();

        this.state = {

            accomcate: null,

            addroom: ['one'],

            isLoading: true,

        }

      }

     handleClick = event => {

        const htmlId = nextId()

        event.preventDefault()

        const addroom = this.state.addroom

        this.setState({ addroom: htmlId })

        return (   

            <div>


                {this.state.addroom.map(addrooms => (

                  <button key= {addroom.id} className={addrooms.modifier}>

                    {addrooms.context}

                  </button>

                ))}

           </div>   

          );

    }




    render() {

         return(

           <div>

           <button onClick={this.handleClick}>Add</button>

           </div>


        )



    }



}

}

任何人都知道是什么原因造成的以及我们如何解决它?


翻阅古今
浏览 104回答 1
1回答

函数式编程

您的代码有一些问题。首先,addroom您的状态是构造函数中的字符串数组,但是在handleClick您设置它的方法this.setState({ addroom: htmlId })中,它将设置为 astring并且在string类型上map未定义函数,因此出现错误。您应该向数组中添加一个项目,例如this.setState({ addroom: [...this.state.addroom, htmlId] })其次,你handleClick不应该返回 jsx,如果你想为你的addroom数组渲染数据,你应该在render方法中这样做,并且handleClick你应该只修改addroom状态变量。您可以像这样实现:render() {&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <button onClick={this.handleClick}>Add</button>&nbsp; &nbsp; &nbsp; {this.state.addroom.map((addroom) => (&nbsp; &nbsp; &nbsp; &nbsp; <button>{addroom}</button>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp; </div>&nbsp; &nbsp; )}最后,您的addrom变量只是一个字符串数组,因此您无法访问id,modifier和context该数组中的一个项目。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答