Why does Appbase return 'undefined' before returning the correct item?

前端 未结 2 1174
一生所求
一生所求 2021-01-15 05:56

I am playing around with AppBase.io as a database and I don\'t understand why this component renders twice after getting an item? It seems as if the AppBase \"database\" ret

2条回答
  •  借酒劲吻你
    2021-01-15 06:23

    It doesn't. The asynchronous call you start in componentWillMount doesn't hold up the rendering process (which is good), so render is called before the call completes, so this.state.item._id is undefined because at that point, this.state.item is '' (the value you set in your constructor).

    This is perfectly normal, just ensure that you render the component in an appropriate way for when it doesn't have the information yet, e.g.:

    var appbaseRef = new Appbase({
      url: "https://JHtFTzy4H:d083068b-596c-489d-9244-8db2ed316e79@scalr.api.appbase.io",
      app: "winwin"
    });
    
    
    class ItemFull extends React.Component {
      constructor() {
        super();
        this.state = {
          item: ''
        }
      }
    
      componentWillMount() {
        appbaseRef.get({
          type: "items",
          id: 'AWI5K7Q-5Q83Zq9GZnED'
        }).on('data', (response) => {
          this.setState({
            item: response
          });
    
        }).on('error', function(error) {
          console.log(error)
        })
      }
    
    
      render() {
        return 
    {this.state.item._id ? this.state.item._id : "loading..."}
    ; } } ReactDOM.render(, document.getElementById('root'));
    
    
    
    
    

    If the component shouldn't be rendered at all before you have that information, then you're requesting it in the wrong place. :-) You'd request it in the parent component and only render this component when you have the information (passing the information in props), something like this:

    var appbaseRef = new Appbase({
      url: "https://JHtFTzy4H:d083068b-596c-489d-9244-8db2ed316e79@scalr.api.appbase.io",
      app: "winwin"
    });
    
    class ParentComponent extends React.Component {
      constructor(...args) {
        super(...args);
        this.state = {item: null};
      }
      
      componentWillMount() {
        appbaseRef.get({
          type: "items",
          id: 'AWI5K7Q-5Q83Zq9GZnED'
        }).on('data', (response) => {
          this.setState({
            item: response
          });
        }).on('error', function(error) {
          console.log(error)
        })
      }
      
      render() {
        return this.state.item ?  : 
    loading...
    ; } } class ItemFull extends React.Component { render() { return
    {this.props.item._id}
    ; } } ReactDOM.render( , document.getElementById('root'));
    
    
    
    
    

提交回复
热议问题