本站PHP后端接口: http://code.liuxinxiu.com/php/Interface/Jsoncallback.php?GUID=1&&Jsoncallback=1
本实例用 ES6 + JSX 语法编写[对应实例] : http://liuxinxiu.com/React_Ajax_setState_Render_UI_ES6/
JavaScript代码
- //import React, { Component, PropTypes } from 'react'
- //import $ from 'n-zepto'
- var React=require('react'); //Es-5
- var $=require('n-zepto'); //Es-5
- //import * as from './commentList.js'
- //import list from './commentList.js';
- /****** 外部子组件map数组当做模板之用 ******/
- var MoviesList = React.createClass({
- render: function () {
- // this.props 用于从组件外部传入数据
- ar _movies = this.props._movies;
- return (
- <li className="datali">
- {_movies.id}-{_movies.name}
- </li>
- )
- }
- });
- /****** 本地模拟Array数据******/
- var movies = [
- {
- id: 1,
- name: '速度与激情001',
- date: 2011
- },
- {
- id: 2,
- name: '速度与激情002',
- date: 2009
- }
- ];
- /****** 使用Es5语法 React.createClass 创建一个组件 ******/
- var DemoComponent = React.createClass({
- /****** 使用 getInitialState 的返回值作为数据的默认值 ******/
- getInitialState: function () {
- // this.state 用于存储数据comments被Ajax赋值要先定义个名称
- return {
- loading: true,
- title: '我喜欢的电影',
- movies: [],
- comments: []
- }
- },
- componentDidMount: function() {
- $.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 slist=JSON.stringify(this.state.comments);
- console.log(slist)
- //console.log(this.state.comments+'33')
- }.bind(this),
- error: function(xhr, type){
- alert(xhr+type+'Ajax error!'); //error
- }
- });
- //console.log(this.state.comments+'++++--!!'); //ajax底下拿不到结果因为提前于异步
- },
- render: function () {
- // this.state 用于存储当前的数据
- var comments = this.state.comments;
- //var dataHtml=movies.map(<p>{name}</p>);// 注意这里 bind(this) 修正了上下文
- /****** Movies子模板 ******/
- function renderMovies({id,name}){
- return <li>{id}-{name}</li>;
- }
- /****** Movies大模板[内嵌子模板] ******/
- //var dataHtml = movies.map(renderMovies);
- /****** Movies大模板[外调子模板] ******/
- var dataHtml = movies.map(function(movies){
- return (
- <MoviesList _movies={movies}/>
- )
- }.bind(this));// 注意这里 bind(this) 修正了上下文
- //console.log('movies:'+movies+'--'+'dataHtml:'+dataHtml);
- /****** Ajax子模板******/
- function renderComment({plat,type,name,guid,cre_time,lottery}){
- return <li>{plat}--{type}--{name}--{guid}--{cre_time}--{lottery}</li>;
- }
- /****** Ajax大模板 ******/
- var AjaxHtml = this.state.comments.map(renderComment);
- //var AjaxHtml='11'
- console.log('comments:'+comments+'--'+'AjaxHtml:'+AjaxHtml);
- return (
- <ul>{AjaxHtml}</ul>
- )
- }
- });
- /****** ES5输出给router ******/
- module.exports=DemoComponent;
- /****** ES6输出给router ******/
- //export default DemoComponent;