【问题标题】:how to get data from server if not already in store如果尚未在存储中,如何从服务器获取数据
【发布时间】:2015-10-31 12:36:59
【问题描述】:

我的 React 应用程序中有一条路线,我可以从两个不同的方向进入,具有不同的含义。

在我的应用主页上,我有一个博客文章列表。如果我单击指向特定博客文章的链接(进入此路由的第一种方式),BlogPost 组件可以通过加载主页时填充的 id 从 BlogPostStore 获取博客文章数据(并将所有博客文章加载到商店)。但是,我也可以从博客的管理页面(不是 React 应用程序)输入相同的路由,从而绕过主页,这意味着博客文章不在商店中。事实上,如果我这样进入路线,商店是空的。

如果我以第一种方式输入路线,商店可以退回博客帖子而不会出现这样的问题,只需退回帖子即可

 getPost: function(id){
    return _posts[id];
 }

但是,如果要考虑进入未填充商店的路线的第二种方式,我需要做这样的事情,[这有明显的问题]通过使用带有 ajax 请求的 return 语句创建@987654321 @

 getPost: function(id){
    if (!_posts[id]){
      /// ajax request
    }
    return _posts[id];
 }

问题:如何重构 BlogStore 的 getPost 函数,以在帖子在商店中时返回帖子,但在帖子不在商店中时回退到 ajax 请求?

注意,我不认为这是我链接到的问题的重复,因为在我的问题中,我首先尝试从商店中检索一个项目(这需要返回它),然后再返回一个 ajax 请求,如果商店未填充。

代码:

BlogPost component

    getInitialState(){
         return this.getStateFromStore()

    },
    getStateFromStore(props){
        return {
            post:  BlogStore.getPost(id)
         }
    },
    render: function(){
        return (
             <div> {post.title} </div>
         )
    }

The BlogStore

     _posts = {}
     init(){
        getJSON(API, function(err, res){
             res.forEach(function(post){
              _posts[post.id] = post;
             }
        }
     }
     getPosts: function(){ 
     },
     getPost: function(id){
        return _posts[id];
     }


function getJSON(url, cb){
    var req = new XMLHTTPRequest()
    req.onload = function(){
        if(req.status === 404){
           cb(new Error('not found');
         }else{
           cb(null, JSON.parse(req.response);
         }
    }
    req.open('GET', url)
    req.setRequestHeader('authorization', localStorage.token)
    req.send()
}

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    请注意,this.emit('gotPosts') 将采用您的商店支持的任何风格。

    The BlogStore
    
         _posts = {}
         init(){
           this.getPosts();
         }
         getPosts: function(){ 
            getJSON(API, function(err, res){
                 res.forEach(function(post){
                  _posts[post.id] = post;
                 }
                 this.emit('gotPosts');
            }
         },
         getPost: function(id){
            var returnPost = _posts[id];
            if (returnPost == null) this.getPosts();
            return returnPost;
         }
    
    
    function getJSON(url, cb){
        var req = new XMLHTTPRequest()
        req.onload = function(){
            if(req.status === 404){
               cb(new Error('not found');
             }else{
               cb(null, JSON.parse(req.response);
             }
        }
        req.open('GET', url)
        req.setRequestHeader('authorization', localStorage.token)
        req.send()
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 2023-03-03
      • 2018-02-11
      • 1970-01-01
      相关资源
      最近更新 更多