簡體   English   中英

從反應組件進行 REST 調用

[英]Making REST calls from a react component

我正在嘗試從反應組件進行 REST 調用並將返回的 JSON 數據呈現到 DOM 中

這是我的組件

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?
        );
    }

為了將返回的 json 綁定到 DOM 中?

您的代碼中有幾個錯誤。 可能讓你this.setState({items:result.json()})this.setState({items:result.json()})

Fetch 的.json()方法返回一個 promise,因此需要將其作為異步處理。

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

我不知道為什么.json()返回一個承諾(如果有人可以闡明,我很感興趣)。

對於渲染功能,你去吧...

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

不要忘記唯一鍵!

對於另一個答案,不需要綁定地圖。

在這里它正在工作......

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

你可以為你的渲染方法試試這個:

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

並且不要忘記使用.bind(this)為您的fetch(...).then() ,我認為沒有...

Fetch 方法將返回一個 Promise,這使得編寫以異步方式工作的代碼變得簡單:

在你的情況下:

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()返回一個承諾,因為它適用於響應流,我們需要首先處理整個響應才能工作。

請改用以下內容。 它會起作用:(如果在控制台中加載,您也可以檢查數據)


 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)
            })
    }

然后使用渲染期間存儲在 state 中的結果根據需要顯示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM