javascript - 在第二次请求后,react-http-request 不会更改加载状态

标签 javascript reactjs

我现在在 React.js 组件中使用react-http-request 来发送请求并处理响应。传递的URL参数与组件状态相关,当状态改变时,组件将重新渲染并改变组件显示。

这适用于第一个请求。但是,我发现该组件在第二次请求后没有返回 {load: true},我想知道如何解决这个问题。

我尝试调用 onRequest 方法并设置组件的加载状态,但请求完成后无法更改加载状态(因为渲染函数无法更改状态)。

react-http-请求:https://github.com/mbasso/react-http-request

我的代码如下:

var FilmList = React.createClass({
    getInitialState: function(){
        return {
            queryType: this.props.queryType
        }
    },
    // ... details emitted.
    render: function(){
        return (<Request
            url={config.url.api + "/" + this.state.queryType}
            method="get"
            accept="application/json"
            query={{ several parameter }}
        >
        {
            ({error, result, loading}) => {
                if (loading || error) {
                    return <Loading />
                }
                else {
                    // process the result here.
                }
            }
        }
        </Request>)
    }

最佳答案

因此,我最初的建议是您使用一些状态管理库(redux、mobx 等),但没有必要获取代码的工作示例,因此:

import fetch from 'whatwg-fetch'; // gives compatibility with older browsers

var FilmList = React.createClass({
    getInitialState: function(){
        return {
            queryType: this.props.queryType,
            content: null
        }
    },

    componentWillMount: function() {
      this.fetchContent();
    },

    fetchContent: function() {
        const uri = config.url.api + "/" + this.state.queryType;
        // You can use w/e you want here (request.js, etc), but fetch is the latest standard in the js world
        fetch(uri, {
          method: 'GET',
          // More properties as you see fit 
        })
        .then(response => response.json()) // might need to do this ;)
        .then(response => {
          this.setState({
            content: response
          })
        })

    },

    // ...

    render: function(){
        const content = this.state.content? (
          // render your content based on this.state.content
        ): (
          <Loading />
        )

        return content;
    }
});

尚未测试此代码,但它有一些很好的好处:

  • http 请求不依赖于 React,理论上应该是针对 UI 组件的。
  • 获取机制是解耦的,可以在组件生命周期的任何时刻重用
  • 我认为更容易阅读,分为更小的逻辑 block

我建议阅读 React Component Lifecycle .

关于javascript - 在第二次请求后,react-http-request 不会更改加载状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41918931/

相关文章:

javascript - React.cloneElement/HOC/嵌入

javascript - 在功能组件之前添加 async 会导致它返回一个对象吗?

reactjs - 如何使用数据库条目在 React Native 中渲染样式?

javascript - 在 React Native Picker 中仅渲染唯一标签

javascript - 是否可以将服务器流身份验证用作不支持 JavaScript 库的浏览器的 Google Drive 客户端身份验证的后备?

javascript - 我应该在 Node js 中使用 var 还是使用 es6 约定

javascript - 如何使用Webpack预编译数据?

reactjs - 即使在调试中,React Native Testing Library仍找不到文本

javascript - 同时打开两个下拉菜单的问题

javascript - 使 Angular Directive(指令)链接功能作为预链接?