如何循环数组中的对象和对象中的对象?React

omjgkv6w  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(214)

我在react中做前台工作,我在使用laravel提供的微服务,它唯一能做的就是返回一个包含国家列表的json,但我不能循环访问对象,我使用了map和for,但没有任何效果,因为微服务返回纯文本json,我首先通过json.parse来创建一个对象,该对象如下所示:
响应微服务的json.parse之后的对象
以下是我如何使用axios请求的代码:

class MisDatosEmprendedor extends React.Component {
  constructor(props){
        super(props);
        this.state = {
          country:'',
        }
   }
   async componentDidMount() {
        await axios({
            url: `${countryUrl}`,
            method: 'GET',
        })
        .then(response =>{
            var objson = JSON.parse(response.data);
            this.setState({
                country: objson,
            })
        })
        .catch(error => {
            console.log(error)
            return error;
        });
   }

}

现在我尝试使用map循环渲染并显示select中的所有国家,但它告诉我这个.state.country.countries未定义错误

render(){
        return <React.Fragment>
       {this.state.country.countries.map(function(d){
                            return(
                                <option value={d.id}>{d.name}</option>
                            )
                        })}
      </React.Fragment>
    }
cwtwac6a

cwtwac6a1#

我会将国家的状态初始化为这样一个对象 country: {countries: []} 不是空字符串。由于您的组件已经装入,它正在读取一个空字符串,因此您有错误。

lyr7nygr

lyr7nygr2#

您的初始状态与api中的数据不匹配。在请求成功之前,它将抛出一个错误。尝试:

constructor(props){
        super(props);
        this.state = {
          country: { countries: [] },
        }
   }

相关问题