React - 用户定义的 JSX 组件不呈现

React - User-Defined JSX Components Not rendering

我一直在尝试进行 AJAX 调用,然后在检索到它后将其添加到我的视图中。

当前代码实际上没有任何变化。

const View = () => (
    <div>
     <h1>Reports</h1>
   <statisticsPage />
    </div>
);
export default View;


var statisticsPage = React.createClass({
  getInitialState: function() {
     return {info: "loading ... "};
  },
  componentDidMount: function() {
     this.requestStatistics(1);
  },
  render: function() {
    return (
        <div>info: {this.state.info}</div>
    );
  },
  requestStatistics:function(){
      axios.get('api/2/statistics')
      .then(res => {
        values = res['data']
        this.setState({info:1})
        console.log('works!!')
      });

    }

  })

您的组件名称必须以大写字符开头,因为以小写字母开头的将作为默认 DOM 元素进行搜索,例如 div, p, span etc。您的 statisticsPage 组件不是这种情况。将其设为大写即可。

根据 docs:

When an element type starts with a lowercase letter, it refers to a built-in component like or and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like <Foo /> compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file.

We recommend naming components with a capital letter. If you do have a component that starts with a lowercase letter, assign it to a capitalized variable before using it in JSX.

const View = () => (
    <div>
     <h1>Reports</h1>
   <StatisticsPage />
    </div>
);



var StatisticsPage = React.createClass({
  getInitialState: function() {
     return {info: "loading ... "};
  },
  componentDidMount: function() {
     this.requestStatistics();
  },
  render: function() {
    return (
        <div>info: {this.state.info}</div>
    );
  },
  requestStatistics:function(){
        console.log('here');
        this.setState({info:1})
        console.log('works!!')
      

    }

  })

ReactDOM.render(<View/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="app"></div>