标题:React - ES6 - Ajax获取接口数据渲染到UI组件【完整示例】 出处:刘新修 时间:Sat, 24 Sep 2016 01:22:55 +0000 作者:刘新修 地址:http://liuxinxiu.com:80/React_Ajax_setState_Render_UI_ES6/ 内容: 本站PHP后端接口: http://code.liuxinxiu.com/php/Interface/Jsoncallback.php?GUID=1&&Jsoncallback=1 本实例用 ES5 + JSX 语法编写[对应实例] : http://liuxinxiu.com/React_Ajax_setState_Render_UI_ES5/ JavaScript代码 /****** ES6输入文件[调用模块依赖] ******/ import React, { Component, PropTypes } from 'react' import $ from 'n-zepto' /****** ES5输入文件[调用模块依赖] ******/ //var React=require('react'); //var $=require('n-zepto'); //import * as from './commentList.js' //import list from './commentList.js'; /****** 本地模拟Array数据******/ var movies = [ { id: 1, name: '速度与激情001', date: 2011 }, { id: 2, name: '速度与激情002', date: 2009 } ]; /****** 外部子组件map数组当做模板之用 ES5 + JSX 语法编写 ******/ var MoviesList = React.createClass({ render: function () { // this.props 用于从组件外部传入数据 var _movies = this.props._movies; return (
  • {_movies.id}-{_movies.name}
  • ) } }); /****** 外部子组件map数组当做模板之用 ES6 + JSX 语法编写 ******/ let CommentList=class CommentList extends Component { constructor(props) { super(props); //ES6调用父类构造函数super不能少! this.state = { wording: '你好呀, ' }; } /****** Ajax子组件中[主体模板] ******/ render(){ return ; } /****** Ajax子组件中[嵌套模板] ******/ renderComment({plat,type,name,guid,cre_time,lottery}){ return (
  • {plat}--{type}--{name}--{guid}--{cre_time}--{lottery}
  • ) } } /****** 使用ES6 + JSX 语法编写 class xx extends React.Component{} 创建一个组件 ******/ class CommentListContainer extends Component { /****** [ES6-constructor||ES5-getInitialState] ******/ constructor(){ super(); this.state = { loading: true, title: '我喜欢的电影', movies: [], comments: [] } } componentDidMount(){ $.ajax({ type: 'GET', url: 'http://code.liuxinxiu.com/php/Interface/Jsoncallback.php', data: {GUID:'1'}, dataType:'jsonp', //告诉Ajax调用$jsonp jsonp: "Jsoncallback", //zpeto-1.2支持自定义回调名 success: function(data){ var yy=JSON.stringify(data); var tlist=JSON.stringify(data.enttityList); //console.log(tlist); //console.log(this.state.title+'22'); this.setState({ comments:data.enttityList, lottery:data.enttityList[0].lottery }); var commentsStr=JSON.stringify(this.state.comments); console.log("\n--->>commentsStr:\n"+commentsStr); //查看获取的数据 //console.log(this.state.comments+'33') }.bind(this), error: function(xhr, type){ alert(xhr+type+'Ajax error!'); } }); //console.log(this.state.comments+'++++--!!'); //ajax底下拿不到结果因为提前于异步 } render(){ return ; } } /****** ES5输出给router ******/ //module.exports=DemoComponent; /****** ES6输出给router ******/ export default CommentListContainer; Generated by Bo-blog 2.1.1 Release