【问题标题】:ReactJS: obtaining JSONReactJS:获取 JSON
【发布时间】:2019-09-09 02:54:45
【问题描述】:

我有一个名为“App”的组件:

export default class App extends Component {

    state = {
        data: {
            id: null,
            created: null
        },
        clicked: false,
        loading: true
    };

    render() {
        const data = this.state.data.id === null ? null : <Data data={this.state.data}/>;
        const title = this.state.clicked ? <TitleDone/> : <Title/>;

        return (
            <div>
                {title}
                <div className="main">
                    <button
                        className=" btn btn-outline-secondary"
                        onClick={() => {
                            this.setState(() => {
                                return {
                                    data: api.getResource(),
                                    clicked: true
                                };
                            });
                        }}>
                        Нажать
                    </button>
                </div>
                <div className="main">
                    {data}
                </div>

            </div>
        );
    }
}

当我按下 Button 时,组件“Api”向后端发送请求,我用 2 个字段重新接收 JSON:id,created。

请求:

getResource = async () => {
    const res = await fetch(`${this._apiPath}${this._logUrl}`);

    if (!res.ok) {
        throw new Error(`Could not fetch ${this._logUrl}` +
            `, received ${res.status}`)
    }
    return await res.json();
};

res.json():

Network.Response:

{"id":87,"created":"2019-04-18 17:26:28.948"}

正如我们所见,JSON 封装在 Promise 中。 它以未定义的形式进入“应用程序”,响应后 this.state.data 看起来像:

data: {
    id: undefined,
    created: undefined
}

请给我建议,如何正确获取数据并将其发送到组件“App”。或者,可能还有其他方法可以做到这一点?

【问题讨论】:

  • api.getResource() 可能是一个异步调用,这就是您获得返回值undefined 的原因。
  • async 函数总是返回一个承诺。

标签: javascript reactjs async.js


【解决方案1】:

getResource 是异步的,因此您需要等待返回的 promise 被解析,然后才能将其置于组件状态。

<button
  className=" btn btn-outline-secondary"
  onClick={async () => {
    this.setState({
      data: await api.getResource(),
      clicked: true
    });
  }}
>
  Нажать
</button>

【讨论】:

    【解决方案2】:

    而且你不需要等待返回 res.json()

    getResource = async () => {
        const res = await fetch(`${this._apiPath}${this._logUrl}`);
    
        if (!res.ok) {
            throw new Error(`Could not fetch ${this._logUrl}` +
                `, received ${res.status}`)
        }
        return res.json();
    };
    

    【讨论】:

      猜你喜欢
      • 2020-03-24
      • 2021-05-22
      • 2020-08-27
      • 1970-01-01
      • 2019-09-03
      • 2016-12-25
      • 2018-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多