简体   繁体   中英

i cant use the map function TypeError: Cannot read property 'map' of undefined

i just enter to "REACT " world to do my front-end off my own project and i have problem for 2 day with the function map , i get data from my back-end and i just save the id in the Cuartos array , i dont know what its my error , i try it with for loop with console.log in a function out of render and it work , but work out of the render function how i can resolve it ? i need to get all the cuarto id in the render this is my code

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

Update: i change the code and i change my state in the componentDidMount and this is my data array of Cuartos how i need to use the map function

enter image description here

Make your api call in componentDidMount and save your data to state and then manipulate your data before rendering.

class FormInterruptor extends React.Component {
    constructor (){
        super();
        this.state = {
            IdInterruptor: '',
            IdCuarto: '',
            Pin: '',
            Dimmer: '',
            Cuartos:[]
          };
        }
         componentDidMount(){
         axios.get("http://localhost:5000/API/Cuartos")
        .then(response => this.setState({Cuartos:res.data}));
         }
          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 中进行调用 Javascript 是异步的,因此当使用 axios 进行调用时,它不会等到响应返回它会继续呈现组件,您需要更新收到响应后的组件如果您仍想使用现有代码进行渲染,请在 axios 回调中的 for 循环之后添加以下行

this.setState({"Cuartos": Cuartos})

First and foremost, what you should be doing is to make the HTTP request in theComponentDidMount lifecycle hook instead of the constructor, as the purpose of the constructor is only for

  • 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 });
    });

}

Then, on your render, you should carry out a check such that you will only carry out Array.map() when the request is returned, and that Cuartos is defined, and the idcuartos array is not empty.

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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