【问题标题】:Problem with loading JSON file in React Router在 React Router 中加载 JSON 文件的问题
【发布时间】:2020-05-26 06:34:55
【问题描述】:

我尝试在此 API 链接中仅获取名称所在的区域,但它显示了 setState 的属性中的错误。语法问题还是别的什么?

顺便问一下:为什么我用这个case,map函数?以备将来之用。

谢谢!

应用 Js:

import React from 'react';
import './App.css';
import Region from './region';
import {BrowserRouter,Switch,Route} from "react-router-dom";

function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <Switch>
          <Route exact path = "/" component={Region}/>
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;

组件:

import React, { Component } from "react";

class Region extends Component {
    constructor (props) {
        super (props)
        this.state = {
            items:[],
            isLoad:false
        }
    }

    ComponentDidMount () {
        fetch("https://restcountries.eu/rest/v2/region/europe").then(res=>res.json()).then(JSON=> {
            this.setState ({
                isLoad = true,
                items = JSON,
            }) 
        })
    }

    render () {
        let {isLoad,items} = this.state;

        if(!isLoad) {
            return <div>Loading...</div>
        }

        else {
            return <div>
                <ul>
                    {items.map(items=>(
                        <li key={items.name}> </li> 
                    ))}
                </ul>
            </div>
        }
    }
}

export default Region;

json 文件:https://restcountries.eu/rest/v2/region/europe

【问题讨论】:

    标签: javascript json reactjs api react-router


    【解决方案1】:

    .map() 背后的原因是您有机会通过访问每个元素并返回不同的方式、结构来操作数组元素。在 React 案例中,它有助于为 render() 方法呈现正确的 JSX 元素。建议阅读 React 官方文档中的Lists and Keys

    阅读Array.prototype.map() 文档:

    map() 方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。

    第一个问题是错误地将属性传递给setState(),请注意我使用的是: 而不是=。尝试更改如下:

    this.setState({
       isLoad: true,
       items: JSON,
    });
    

    此外,您可以尝试以下方法 - 当前元素的名称与数组本身的名称相同 - 最好使用不同的名称:

    return <div>
         <ul>
             {items && items.map(e => <li key={e.name}> {e.name} </li>)}
         </ul>
    </div>
    

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2016-01-22
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多