六、React JOSN数据传递获取
修改main.js CommentBox标签
<CommentBox url="app/comments.json"/>,document.getElementById('app')
在 app 文件夹下 新建 comments,json 文件
[ {"author": "journey" , "date" : "3分钟前" , "text" : "今天天气有点冷!"}, {"author": "jim" , "date" : "5分钟前" , "text" : "今天早上吃了两个面包!"} ]
回到CommentBox.js
这里使用Ajax方式获取JSON数据
所有需要导入jquery来使用Ajax
使用
jspm install jquery
来安装jquery
使用import引入jquery
import $ from 'jquery';
然后在class CommentBox extends React.Component{}中使用constructor这个函数
constructor(props){ super(props); this.state = {data: []}; $.ajax({ url: this.props.url, datatype: 'json', cache: false, success: comments => { this.setState({ data: comments }); }, error: (xhr , status , error) => { console.log(error); } }); }
刷新页面
进入到CommentBox.js
将$.ajax请求单独放入一个方法内
getComments(){ $.ajax({ url: this.props.url, datatype: 'json', cache: false, success: comments => { this.setState({ data: comments }); }, error: (xhr , status , error) => { console.log(error); } }); }
然后在constructor方法内进行调用,使用setInterval 定时器并设置每隔5000ms执行一次getComments方法
this.getComments(); setInterval(() => this.getComments(),5000);
页面效果