如何在数据准备好后呈现组件? [英] How do I render a component when the data is ready?

查看:119
本文介绍了如何在数据准备好后呈现组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在试图弄清楚如何在数据准备好时填充/渲染组件?基本上我有一个查询我的服务器的脚本返回数据,然后我解析它并使其成为一个具有我需要的属性的集合。然后在另一个文件中,我有反应组件正在寻找该对象,但它们同时运行,因此当组件正在寻找它时该对象不存在。

I'm trying to figure out how to populate/render a component when the data is ready? Essentially I have a script that queries my server which returns data, then I parse it and make it into an collection with the properties I need. Then in another file, I have the react component that's looking for that object but they're running at the same time so the object doesn't exist when the component is looking for it.

我不知道如何继续。

这是我的组件:

let SliderTabs = React.createClass({
    getInitialState: function() {
        return { items: [] }
    },
    render: function() {
        let listItems = this.props.items.map(function(item) {
            return (
                <li key={item.title}>
                    <a href="#panel1">{item.title}</a>
                </li>
            );
        });

    return (
            <div className="something">
                <h3>Some content</h3>
                    <ul>
                        {listItems}
                    </ul>
            </div>
        );
    }
});

ReactDOM.render(<SliderTabs items={home.data.slider} />,                
    document.getElementById('slider-tabs'));

我如何获取数据:

var home = home || {};

home = {
  data: {
    slider: [],
    nav: []
  },
  get: function() {

    var getListPromises = [];

    $.each(home.lists, function(index, list) {
      getListPromises[index] = $().SPServices.SPGetListItemsJson({
        listName: home.lists[index].name,
        CAMLViewFields: home.lists[index].view,
        mappingOverrides: home.lists[index].mapping
      })
      getListPromises[index].list = home.lists[index].name;
    })

    $.when.apply($, getListPromises).done(function() {
      home.notice('Retrieved items')
      home.process(getListPromises);
    })
  },
  process: function(promiseArr) {
    var dfd = jQuery.Deferred();

    $.map(promiseArr, function(promise) {
      promise.then(function() {
        var data = this.data;
        var list = promise.list;

        // IF navigation ELSE slider
        if (list != home.lists[0].name) {
          $.map(data, function(item) {
            home.data.nav.push({
              title: item.title,
              section: item.section,
              tab: item.tab,
              url: item.url.split(",")[0],
              path: item.path.split("#")[1].split("_")[0]
            })
          })
        } else {
          $.map(data, function(item) {
            home.data.slider.push({
              title: item.title,
              url: item.url.split(",")[0],
              path: item.path.split("#")[1]
            })
          })
        }
      })
    })

    console.log(JSON.stringify(home.data))
    dfd.resolve();
    return dfd.promise();
  }
}

$(function() {
  home.get()
})


推荐答案

在React中执行此操作的常用方法是跟踪何时获取数据。这可以通过例如完成。通过在您所在的州拥有 isFetching 字段:

A common way to do this in React is to keep track of when data is being fetched. This can be done e.g. by having a isFetching field in your state:

// This would be your default state
this.state = {
  isFetching: false
};

然后,当您触发请求时(最好在componentDidMount中),您设置 isFetching 使用:

Then, when you fire off the request (preferably in componentDidMount) you set isFetching to true using:

this.setState({ isFetching: true });

最后,当数据到达时,再次将其设置为false:

And finally, when the data arrives, you set it to false again:

this.setState({ isFetching: false });

现在,在你的渲染功能中,你可以这样做:

Now, in your render function you can do something like this:

render () {
 return (
    <div className="something">
      <h3>Some content</h3>
      {this.state.isFetching ? <LoadingComponent /> : (
         <ul>
           {listItems}
         </ul>
      )}
    </div> 
  )
}

通过使用州,您不必担心告诉您的组件执行某些操作,而是对状态中的更改做出反应并相应地呈现它。

By using state, you don't have to worry about telling your component to do something, instead it reacts to changes in the state and renders it accordingly.

更新:

如果您计划实际使用React,我会建议您将您的方法改为我上面所描述的内容(在 React docs中阅读更多内容)。也就是说,将您在 get 函数中的代码移动到React组件的 componentDidMount 函数中。如果那是不可能的,你可能只是等待打电话

If you plan on actually using React, I'd suggest you change your approach into what I've described above (read more in the React docs). That is, move the code you have in your get function into your React component's componentDidMount function. If that's not possible, you can probably just wait to call

ReactDOM.render(
  <SliderTabs items={home.data.slider} />,                
  document.getElementById('slider-tabs')
);

直到您的数据到达。

这篇关于如何在数据准备好后呈现组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆