将Fetched JSON数据设置为state并使用它

问题描述 投票:2回答:2

我是React的新手,所以我正在努力学习基本概念。

我通过API获取数据我将一些数据硬编码为学习目的,提取请求如下:

componentDidMount() {
    fetch("myserver.com/api/a/1")
    .then(function(response) {
        response.json()
    })
}

在我的构造函数中,我将状态设置为data:'false':

constructor(props) {
    super(props)

    this.state = {data: 'false'};
}

但是从这里开始,我迷失了。我在JSON对象中有三个不同的字符串,我通过我的API,但我不知道如何访问它们。我已经尝试在componentDidMount中设置setState但是我遇到了很多错误。

在这样的情况下你怎么办?我应该在哪里设置状态,以及如何通常访问/迭代JSON对象?

提前致谢!

json reactjs fetch-api
2个回答
2
投票

尝试这样的事情:

export default class YourComponent extends React.Component {

    constructor(props) {
        super(props);

        this.state = {data: 'false'};
    }

    componentDidMount() {
        this._getData();
    }


    _getData = () => {
        fetch("myserver.com/api/a/1")
        .then(response => {
            if (response.ok) {
                    return response;
            } else {
                let errorMessage = `${response.status(${response.statusText})`,
                error = new Error(errorMessage);
                throw(error);
            }
        })
        .then(response => response.json())
        .then(json =>{
           console.log(json);
           this.setState({ data: json.data })
        });
    }

    render() {
        return (
            <div>
               {
                this.state.data &&
                this.state.data.map( (item, key) =>
                    <div key={key}>
                        {item}
                    </div>
                )}
            </div>
        )
    }
}

0
投票

正确的做法是调用JSON.parse()方法。

    _getData = () => {
                fetch("myserver.com/api/a/1")
                .then(response => {
                   if (response.ok) {
                   return response;
                 } else {
                 let errorMessage = 
                     `${response.status(${response.statusText})`,
                  error = new Error(errorMessage);
                  throw(error);
                 }
                })
                .then(response => response.json())
                .then(json =>{
                   console.log(json);
                   this.setState({ data: JSON.parse(json) })
                });
          }
© www.soinside.com 2019 - 2024. All rights reserved.