javascript - 我无法使用 map 功能 TypeError : Cannot read property 'map' of undefined

标签 javascript java html ajax reactjs

我刚刚进入“REACT”世界来完成我自己项目的前端,我在函数映射方面遇到了 2 天的问题,我从后端获取数据,我只是将 id 保存在 Cuartos 中数组,我不知道我的错误是什么,我在渲染之外的函数中使用 console.log 的 for 循环尝试它并且它可以工作,但是在渲染函数中工作我如何解决它?我需要获取渲染中的所有 cuarto id 这是我的代码

class FormInterruptor extends React.Component {
    constructor (){
        super();
        const axx={au:[]};
        const Cuartos = [];
        axios.get("http://localhost:5000/API/Cuartos")
        .then(response => {

           const  a=JSON.stringify(response.data);
            console.log(response.data);
            axx.au=response.data;
           const b=JSON.stringify(axx.au.idcuarto);
            console.log("aqui estas" )
           for (let i = 1; i < b.length; i=i+2)
           {
                 Cuartos.push({idcuarto:parseInt((JSON.stringify(axx.au.idcuarto))[i])});
             }
        });


        this.state = {
            IdInterruptor: '',
            IdCuarto: '',
            Pin: '',
            Dimmer: '',
            Cuartos
          };


        }

          onChange(e){
            this.setState({
              [e.target.name]:e.target.value
                     });
          }

      handleSubmit = event => {
            event.preventDefault();

            const Luz = {
              IdInterruptor: this.state.IdInterruptor,
              IdCuarto: this.state.IdCuarto,
              Pin: this.state.Pin,
              Dimmer: this.state.Dimmer

            };

            //AYUDA CON EL LUGAR DODNE SE PONDRA EL INTERRUPTOR 

            let config = {headers: {'Access-Control-Allow-Origin': "*"}};
            axios.post('http://localhost:5000/API/Cuarto/1/Luz/add',  Luz , config)
              .then(res => {
                //console.log(res);
                console.log(res.data);
              })
          }
    render(){

        return (

          <div className="App">
          <header className="App-header">
          <img src={process.env.PUBLIC_URL + '/Images/Escudo.png'} alt='Escudo' width='400'/>

            <div  className="Formulario"> 
            <h2>
              Formulario Luz
            </h2>
            <form onSubmit={this.handleSubmit} >

                <div id='form'>
               <input  id="form" type="text"placeholder="ID del interruptor" value={this.state.IdInterruptor} name="IdInterruptor" onChange={this.onChange.bind(this)} />
               </div>
               <div id="separador">


               <select   id="form" name="IdCuarto"   value={this.state.IdCuarto} onChange={this.onChange.bind(this)} >

               </select>
               </div>

               <div id="separador">

               <input  id="form" type="text" name="Pin"  placeholder="Pin" value={this.state.Pin} onChange={this.onChange.bind(this)} />
               </div>
               <div id="separador">

               <input id="form" type="text" name="Dimmer"  placeholder ="Dimmer" value={this.state.Dimmer} onChange={this.onChange.bind(this)}/>
               </div>
               <div >
                <input type="submit" value="Submit" className="button" onChange={this.onChange}/>
                </div>


              </form>
              </div>
              <div> 

               {this.state.Cuartos.map(p => {
                       return  <p  > {p.idcuarto} !</p>}
                            )}


              </div>

          </header>
        </div>

        );

    }
    }

    export default FormInterruptor

更新: 我更改了代码并更改了 componentDidMount 中的状态并且 这是我的 Cuartos 数据数组,我需要如何使用 map 功能

enter image description here

最佳答案

首先,您应该做的是在 ComponentDidMount 中发出 HTTP 请求。生命周期钩子(Hook)而不是构造函数,如 purpose构造函数仅用于

  • Initializing local state by assigning an object to this.state. Binding
  • event handler methods to an instance.
constructor(props) {
  super(props);
  this.state = {
    IdInterruptor: '',
    IdCuarto: '',
    Pin: '',
    Dimmer: '',
    Cuartos: undefined,
  }
}

componentDidMount() {
  let Cuartos;
  axios.get("http://localhost:5000/API/Cuartos")
    .then(response => {

       const  a=JSON.stringify(response.data);
        console.log(response.data);
        axx.au=response.data;
       const b=JSON.stringify(axx.au.idcuarto);
        console.log("aqui estas" )
       for (let i = 1; i < b.length; i=i+2) {
         Cuartos.push({idcuarto:parseInt((JSON.stringify(axx.au.idcuarto))[i])});
       }
       this.setState({ Cuartos });
    });

}

然后,在渲染时,您应该执行检查,以便仅在返回请求时执行 Array.map(),并且定义了 Cuartos,并且 idcuartos 数组不为空。

render() {
  const { Cuartos } = this.state;

  return <>
   <div> 
     {
       Cuartos && Cuartos.idcuartos.length && Cuartos.idcuartos.map(p => {
         return . <p>{q}</p>
       })
     }
   </div>
  </>

}

关于javascript - 我无法使用 map 功能 TypeError : Cannot read property 'map' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59496454/

相关文章:

javascript - on.blur 和 on.click 在 ajax 之前触发?

javascript - html5/javascript乘以输入类型并显示在表格中

javascript - javascript中计算不正确的问题

java - 在 Java 中从 PDF 生成 PCL

javascript - 仅在第一次单击按钮时增加计数器

javascript - JW播放器如何添加自定义提示点

java - 如何在 Java 中序列化泛型类?

java - 使用 supportFragmentManager 推送新 Fragment

javascript - reveal.js 如何调整元素的大小?

JavaScript 函数不适用于 anchor 标记点击