首页 > 解决方案 > 拆分方法不适用于字符串?TypeError:无法读取未定义的属性“拆分”

问题描述

这是我关心的代码:
我不确定为什么我不能split()string. 我通常使用split()它,它一直运行良好。这是它第一次不工作。为什么?

import React, { Component } from 'react';
import './App.css';

class App extends Component {
constructor(props){
super(props);

this.state = {
  data: []
}
}

componentDidMount(){
var url = 'https://restcountries.eu/rest/v2/all';

fetch(url)
  .then(data => data.json())
  .then(data => data.map((item, index) => {
    return item.name + " " + item.flag;
  })).then(data => this.setState({data}));

}  

render() {
  var randItems = [];
  var randNum = 0;

  for(let i = 0; i < 4; i++){
    randNum = Math.floor(Math.random() * this.state.data.length);
    randItems.push(this.state.data[randNum]);
  }


var item = randItems[0].split(' ');
console.log('typeof item and its value ' + typeof item + ' ' + item);

注意输出是typeof item,它的值string

北马里亚纳群岛 https://restcountries.eu/data/mnp.svg

标签: split

解决方案


推荐阅读