【问题标题】:State not passed into prop状态未传递到道具
【发布时间】:2015-12-25 00:21:09
【问题描述】:

我正在使用带有 Rails 4 的 React。

我有以下内容:

<%= 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}

所以 props 正在设置,但是设置为字符串而不是 JSON 数组?

【问题讨论】:

    标签: javascript ruby-on-rails json reactjs


    【解决方案1】:

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

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

    要使用 JavaScript 表达式,请仅使用花括号:

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

    【讨论】:

      猜你喜欢
      • 2019-11-30
      • 2020-09-14
      • 1970-01-01
      • 2021-05-24
      • 2018-09-02
      • 2019-12-14
      • 2019-04-05
      • 2020-12-29
      • 2017-05-18
      相关资源
      最近更新 更多