简体   繁体   English

如何解决无法读取 React js 中未定义错误的属性“地图”?

[英]How to solve Cannot read property 'map' of undefined error in React js?

I am building a react js application with dummy backend using json-server .I am implementing a dropdown list but I am getting Cannot read property 'map' of undefined error on fetching from api.The api is working fine in browser but while fetching in react it is giving me this error.我正在使用json-server构建一个带有虚拟后端的 react js 应用程序。我正在实现一个下拉列表,但在从 api 获取时Cannot read property 'map' of undefined error 。api 在浏览器中工作正常,但在获取时反应它给了我这个错误。

My component:我的组件:

import React from 'react';

var values;

class ApiDropDown extends React.Component {

    constructor(){
        super();
        this.state = {
            options: []
        }  
    }

   componentDidMount(){
       this.fetchOptions()
    }

    fetchOptions(){
        fetch('http://localhost:5000/groups')
            .then((res) => {
                
                return res.json();
            }).then((json) => {
                values = json;
                this.setState({options: values.groups})
                console.log(values);
            });
    }
    render(){
    
        return <div>
            <select>
                { this.state.options.map((option, key) => <option key={key} >{option}</option>) }
            </select>
            </div>;
    



}
}

export default ApiDropDown;

My db.json for dummy backend:我的 db.json 用于虚拟后端:

{  
  "groups":[  
     {  
        "key":"version",
        "apis":"system_info"
     },
     {  
        "key":"admin",
        "name":"patients"
     },
     {  
        "id":"admin2",
        "name":"doctors"
     }
     
  ]
}

Here's how I am rendering my ApiDropDown component:这是我渲染 ApiDropDown 组件的方式:

 return (
    <form className="add-form" onSubmit={onSubmit}>
      <div>
      <ApiDropDown/> //ApiDropDown Component
      </div>
      <div >
        <input className="clientparams"
          type="text"
          placeholder="Add Client"
          value={client_name}
          onChange={(e) => setText(e.target.value)}
        />
      </div>
      </form>

Can someone help me with this error?有人可以帮我解决这个错误吗?

You're not using fetch right:您没有正确使用 fetch :

fetch('http://localhost:5000/groups').then((res) => {
  res.json().then((json) => {
    values = json;
    this.setState({options: values.groups})
    console.log(values);
  })
})

Two things that should be correct.两件事应该是正确的。

  1. { this.state.options.map((option, key) => <option key={key} >{option}</option>) } In this you are trying to bind the object as react child, so instead of this it should be {{ this.state.options.map((option, key) => <option key={key} >{option["apis"]}</option>) } { this.state.options.map((option, key) => <option key={key} >{option}</option>) }在此您尝试将 object 绑定为反应子级,所以不是这个它应该是{{ this.state.options.map((option, key) => <option key={key} >{option["apis"]}</option>) }
  2. You no need to declare a variable to store the fetch values you can directly set it to state like this.您无需声明一个变量来存储获取值,您可以像这样直接将其设置为 state。 this.setState({options: json.groups})

Here is the working example of your code(fetch call is different): https://codesandbox.io/embed/nifty-lamport-mzmro?fontsize=14&hidenavigation=1&theme=dark这是您的代码的工作示例(获取调用不同): https://codesandbox.io/embed/nifty-lamport-mzmro?fontsize=14&hidenavigation=1&theme=dark

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

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