状态未传递到道具中

State not passed into prop

本文关键字:状态      更新时间:2023-09-26

我正在使用React with Rails 4。

我有以下内容:

<%= react_component('Box',url: "blah", pollInterval: 2000) %>

然后是我的组件:

var Box = React.createClass({
      getInitialState: function () {
    return {data: []};
  },
  loadStuffFromServer: function() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function(data) {
        this.setState({data: data});
        console.log(data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentDidMount: function() {
    this.loadStuffFromServer();
    setInterval(this.loadStuffFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div>
        <Widget office="1" data="{this.state.data}"/>
      </div>
    );
  }
});
var Widget = React.createClass({
  render: function () {
     return (
        <div>
          {this.props.data}
        </div>
     )
  };
});

对于Box,我可以使用React DevTools For Chrome看到状态被设置为url返回的JSON。然而,对于Widget组件,当我尝试回显道具时,它实际上返回:{this.state.data}

所以道具是被设置的,但设置为字符串而不是JSON数组?

引号内的任何属性都是字符串:

<Widget office="1" data="{this.state.data}"/>

要使用JavaScript表达式,请仅使用curlies:

<Widget office="1" data={this.state.data}/>