简体   繁体   English

如何修复 TypeError:this.state.Templatelist.map 不是反应中的函数?

[英]How to fix TypeError: this.state.Templatelist.map is not a function in react?

I need to display JSON data that is coming from webapi.我需要显示来自 webapi 的 JSON 数据。 I need to fill dropdown with the data in REACT.我需要用 REACT 中的数据填充下拉列表。 I am getting the issue while filling the data in .我在填写数据时遇到了问题。

console.log(this.state.Templatelist) returns the data. console.log(this.state.Templatelist) 返回数据。 this data is coming from api.此数据来自 api。

[{"Template_ID":11,"TemplateName":"All"},{"Template_ID":21,"TemplateName":"Test"}] [{"Template_ID":11,"TemplateName":"All"},{"Template_ID":21,"TemplateName":"Test"}]

Please find my code:请找到我的代码:

import React from "react";
export class test extends React.Component {
       constructor(props) {
             super(props);
             this.state = {
                    CopyFromTemplate_ID: "",
                    Templatelist: [],
             }
             this.handleChange = this.handleChange.bind(this);
       }

       handleChange(event) {
             this.setState({ CopyFromTemplate_ID: event.target.value });

             console.log(event.target.value)

       }
 
       componentDidMount() {
                  this.getTemplateList();
       }

       getTemplateList() {
             fetch(REQUEST_URL)
                    .then(response => response.json())
                    .then((data) => {
                           this.setState({
                                 Templatelist: data,
                                 loading: false
                           })
                           console.log(this.state.Templatelist);
                    })
       }

       render() {
             return (
                    <div>
                           <form onSubmit={this.handleSubmit} >
                                 {this.state.Templatelist}
                         <select size="1" value={this.state.CopyFromTemplate_ID} onChange={this.handleChange} >
       <option></option>
      {this.state.Templatelist.map((item) =>
          <option id={item.Template_ID} value={item.Template_ID}>
              {item.value}
         </option>)
      }
  </select>
</form>
</div>
);

    }

}


export default test;

Thanks谢谢

Since your data is undefined or waiting to arrive, you need to check if it is an array before you render it.由于您的数据未定义或等待到达,因此您需要在渲染之前检查它是否为数组。 You can check if data arrived and if it has a length, if not, then render the loading component.您可以检查数据是否到达以及是否有长度,如果没有,则渲染加载组件。

  {this.state.Templatelist.length? this.state.Template.map((item) =>
          <option id={item.Template_ID} value={item.Template_ID}>
              {item.value}
         </option>) : <p>...loading</p>
      }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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