Aca*_*cai 3 javascript jsx reactjs
我一直在尝试进行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!!')
});
}
})
Run Code Online (Sandbox Code Playgroud)
组件名称必须以大写字符开头,因为以小写字母开头的那些将被搜索为默认DOM元素div, p, span etc.您的statisticsPage组件不是这种情况.使它大写,它工作正常.
根据文件:
当一个元素类型以
lowercase字母开头时,它引用一个内置的组件,如或,并导致'div'传递给字符串或'span'React.createElement.以大写字母开头的类型,例如<Foo />编译到React.createElement(Foo)并对应于JavaScript文件中定义或导入的组件.我们建议使用大写字母命名组件.如果您确实有一个以
lowercase字母开头的组件,请在将其用于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'));Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)