【问题标题】:i cant use the map function TypeError: Cannot read property 'map' of undefined我不能使用地图函数 TypeError:无法读取未定义的属性“地图”
【发布时间】:2020-04-17 04:05:23
【问题描述】:

我刚进入“REACT”世界,在我自己的项目中做我的前端,我的函数映射有 2 天的问题,我从后端获取数据,我只是将 id 保存在 Cuartos数组,我不知道我的错误是什么,我尝试使用for循环和console.log在渲染之外的函数中工作并且它可以工作,但是在渲染函数之外我该如何解决它?我需要在渲染中获取所有 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 数据数组

enter image description here

【问题讨论】:

  • 为什么要对响应进行字符串化?您从constructor 中的 API 调用得到什么响应?
  • 您是否要打印Cuartos 中的所有内容?还是您只想打印一个特定的键?
  • @wentjun 特定键,“idcuartos”

标签: javascript java html ajax reactjs


【解决方案1】:

在 componentDidMount 中调用您的 api 并将您的数据保存到状态,然后在渲染之前操作您的数据。

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

【讨论】:

  • 如果我这样做了,我在 Cuartos 数组中有更多数组,我需要如何使用函数映射?,我用 Cuartos 数组中的数据照片更新问题
【解决方案2】:

您在构造函数中进行了不推荐的调用,请尝试在 componentDidMount 中进行 Javascript 是异步的,因此当使用 axios 进行调用时,它不会等到响应返回它会继续呈现组件,您需要在收到响应后更新组件 如果您仍想使用现有代码进行渲染,请在 axios 回调中的 for 循环之后添加以下行

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

【讨论】:

    【解决方案3】:

    首先,你应该做的是在ComponentDidMount生命周期钩子而不是构造函数中发出HTTP请求,因为构造函数的purpose仅用于

    • 通过将对象分配给 this.state 来初始化本地状态。绑定
    • 实例的事件处理程序方法。
    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>
      </>
    
    }
    

    【讨论】:

    • 我收到 TypeError:无法读取未定义的属性“长度”
    • @Gabo4299 试试这个 Cuartos &amp;&amp; Cuartos.length &amp;&amp; Cuartos.map(...) 我已经更新了我的代码
    • @Gabo4299 opps,我犯了一个错误。认为Cuartos 是一个数组。好的,我已经进行了更改,因此只打印了idcuartos
    • 我只是解决它,它只是 &&Cuartos.map (p=>{retunrt

      {p["idcuartos"]}

      })
    猜你喜欢
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2021-02-25
    • 2018-02-08
    • 2019-10-05
    相关资源
    最近更新 更多