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

Set Fetched JSON data as state and use it

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

我正在通过 API 获取数据 我为了学习目的硬编码了一些数据,使用这样的获取请求:

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

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

constructor(props) {
    super(props)

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

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

在这种情况下你是怎么做的?我应该在哪里设置状态,你通常如何 access/iterate 超过 JSON 个对象?

提前致谢!

尝试这样的事情:

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

正确的做法是调用 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) })
                });
          }