使用webpack编写React时,用ajax获取数据时遇到问题
项目入口文件的代码如下
1 import React from 'react';
2 import CommentBox from './Components/CommentBox';
3
4
5 function main(){
6 React.render(
7 <CommentBox url="./comments.json" pollInterval={2000} />,
8 document.getElementById('app')
9 );
10 }
11
12 main();
CommentBox的代码如下
import React from 'react';
import CommentList from './CommentList';
import CommentForm from './CommentForm';
import $ from 'jquery/src/core';
export default class CommentBox extends React.Component{
loadCommentsFromServer(){
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data){
this.setState({data: data});
}.bind(this),
error: function(err){
console.err(this.props.url,status,err.toString())
}.bind(this)
});
};
getInitialState(){
return {data: []};
};
componentDidMount(){
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer,this.props.pollInterval);
};
render(){
return(
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
};
CommentList的代码如下
import React from 'react';
import Comment from './Comment';
export default class CommentList extends React.Component{
render(){
var commentNodes = this.props.data.map(function(comment){
return(
<Comment author={comment.author}>
{comment.text}
</Comment>
);
});
return(
<div className="commentList">
{commentNodes}
</div>
);
}
}
Comment的代码如下
import React from 'react';
import Showdown from 'showdown';
var converter = new Showdown.Converter();
export default class Comment extends React.Component{
render(){
return(
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
{converter.makeHtml(this.props.children.toString())}
</div>
);
}
}
在浏览器访问的时候却得到如下的结果
-
- Uncaught TypeError: Cannot read property ‘data’ of null * * 是我的请求路径有问题还是代码哪里写错了!求大神解答