json 从反应组件进行 REST 调用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37486251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:26:45  来源:igfitidea点击:

Making REST calls from a react component

jsonrestdomreactjsfetch

提问by user_mda

I am trying to make REST call from a react component and render the returned JSON data into the DOM

我正在尝试从反应组件进行 REST 调用并将返回的 JSON 数据呈现到 DOM 中

Here is my component

这是我的组件

import React from 'react';

export default class ItemLister extends React.Component {
    constructor() {
        super();
        this.state = { items: [] };
    }

    componentDidMount() {
        fetch(`http://api/call`) 
            .then(result=> {
                this.setState({items:result.json()});
            });
    }

    render() {        
        return(
           WHAT SHOULD THIS RETURN?
        );
    }

In order to bind the returned json in a DOM?

为了将返回的 json 绑定到 DOM 中?

回答by D. Walsh

There are a couple of errors in your code. The one that's probably tripping you up is the this.setState({items:result.json()})

您的代码中有几个错误。可能让你绊倒的那个是this.setState({items:result.json()})

Fetch's .json()method returns a promise, so it will need to be dealt with as async.

Fetch 的.json()方法返回一个 promise,因此需要将其作为异步处理。

fetch(`http://jsonplaceholder.typicode.com/posts`)
.then(result=>result.json())
.then(items=>this.setState({items}))

I don't know why .json()returns a promise (if anyone can shed light, I'm interested).

我不知道为什么要.json()返回一个承诺(如果有人可以阐明,我很感兴趣)。

For the render function, here you go...

对于渲染功能,你去吧...

<ul>
   {this.state.items.map(item=><li key={item.id}>{item.body}</li>)}
</ul>

Don't forget the unique key!

不要忘记唯一键!

For the other answer, there's no need to bind map.

对于另一个答案,不需要绑定地图。

Here it is working...

在这里它正在工作......

http://jsfiddle.net/weqm8q5w/6/

http://jsfiddle.net/weqm8q5w/6/

回答by Micka?l R.

You can try this for your render method:

你可以为你的渲染方法试试这个:

render() {
    var resultNodes = this.state.items.map(function(result, index) {
        return (
            <div>result<div/>
        );
    }.bind(this));
    return (
        <div>
            {resultNodes}
        </div>
    );
}

and don't forget to use .bind(this)for your fetch(...).then(), I don't think it could work without...

并且不要忘记使用.bind(this)for your fetch(...).then(),我认为没有...

回答by mohdasha

Fetch methods will return a Promise that makes it straightforward to write code that works in an asynchronous manner:

Fetch 方法将返回一个 Promise,这使得编写以异步方式工作的代码变得简单:

In your case:

在你的情况下:

componentDidMount(){
  fetch('http://api/call')      // returns a promise object
    .then( result => result.json()) // still returns a promise object, U need to chain it again
    .then( items => this.setState({items}));
}

result.json()returns a promise, because this it works on a response streamand we need to process entire response first in order to work.

result.json()返回一个承诺,因为它适用于响应流,我们需要首先处理整个响应才能工作。

回答by Hirak JD

Use the following instead. It will work: (You can also check the data if loaded in the console)

请改用以下内容。它会起作用:(如果在控制台中加载,您也可以检查数据)


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

 componentDidMount() {
        fetch('http://api/call')
            .then(Response => Response.json())
            .then(res => {
                console.log(res);
                this.setState({
                    items: res,
                });
            })
            .catch(error => {
                console.log(error)
            })
    }

Then use the result stored in state during render to display as required.

然后使用渲染期间存储在 state 中的结果根据需要显示。