React 组件继承和 ajax 调用

React component inheritance and ajax calls

我很难理解为什么这不起作用

var link = window.location.href;
var array = link.split('/');
var sub = array[array.length-1];
console.log(sub);
var name;
var posts;
var upvotes;

var ProfileFiller = React.createClass({

   getUser : function() {

   $.ajax({
            url: '/profile/' + sub,
            dataType: 'json',
            success: function(data) {
               this.setState({user:data});
               name = data.local.email;

            }.bind(this),
        error: function(xhr, status, err) {
                console.log("error");
               console.error(this.props.url,status, err.toString());
            }.bind(this)
        });

   },

   getInitialState: function() {
       return {
          user: []

       }
    },


  componentDidMount: function() {
    this.getUser();
    },

  render : function() {
  return(
  <div>
  <hr/>
  <List user = {this.state.user} />
  </div>
  )

  }
});


var List = React.createClass({

  render : function() {
    console.log(this.props.user);
  return (
  <h1>{this.props.user.name}</h1> 
  )
  }
});


React.render(<ProfileFiller  />,
document.getElementById('profileView'));

我记录了多次,我的列表 class 中的数组最初是空的,然后 returns 再次填充了元素。我认为 ajax 调用需要一些时间来提取数据,这就是它不起作用的原因,但它很可能与渲染及其工作方式有关,但是如果我设置全局变量 "name" 并将其分配给发生 ajax 调用的用户子字段,并将其传递为 <h1>{name}</h1> 而不是 <h1>{this.props.user.name}</h1> 它最终起作用了。

我知道反应方式是传递道具而不是设置变量,对此有点困扰。

这里也是 ajax 的服务器端:

app.get('/profile/:user', function(req, res) {
    var id = req.params.user;
    User.findById(id, function(err, user) {
        res.json(user);
    });
 });

编辑: 一些解决方案?: 我能够通过将用户设置为 data.local 来传递它,似乎在使用道具时,当你下降两层 json 时它似乎不起作用,我不知道为什么。所以对我来说 this.props.user.email 比 this.props.user.local.email 更有效。所以我只是将用户设置为 data.local 而不是数据。

另一个问题: 我还有一个问题,有时我的数组会变空,这可能是因为 ajax 调用可能需要一段时间。我该如何解决这样的问题,我会说

if ajaxcall is complete/if success is complete 
   then pass down our filled array

但我认为我们 ajax 的成功调用中的 setstate 会解决这个问题。嗯... 或者有更好的解决方法吗?

修复方法如下:

render : function() {
    console.log(this.props.user);
  return (
  <div><h1>{this.props.user.name}</h1></div>
  )
  }

React 寻找渲染中的所有内容,用 Div 标签包裹,之后用户可以根据需要嵌套。你也可以在 render 下写 var userName = this.props.user.name;,然后在 h1 标签中调用 {userName}。其次,过去的道具由于某种原因不能打印超过 1 级的深度。我不知道这是 "me-type" 问题还是反应问题。

例如,它不会找到 this.props.user.name.firstName,直到 this.props.user.name。