美文网首页
Ajax请求的数据绑定给组件

Ajax请求的数据绑定给组件

作者: 野薇薇 | 来源:发表于2017-02-16 09:49 被阅读0次

用了一天的时间搞这个,踩坑不少

class PrizeItems extends Component{
    constructor(props){
        super(props);
        this.state = {
            posts: []
        };
    };
    componentWillMount(){
        var _this = this;
        var p1 = new Promise(function (res, rej) {
            $.ajax({
                url:"src/data/award.json",
                type:"GET",
                dataType:"json",
                success:function (data) {
                    res(data);
                },
                error:function (data) {
                    rej("请求失败");
                }
            })
        });
        p1.then(function (data) {
            console.log(data);
            const posts = data.awards.map((obj) => obj);
            _this.setState({ posts });
        });
    }
    render(){
        console.log(this.state.posts);
        return(
            <ul>
                {this.state.posts.map((post) =>
                    <PrizeItem key={post.rank.toString()} productName = {post.productInfo.productName} picUrl={post.productInfo.picUrl}>
                    </PrizeItem>
                )}
            </ul>
        )
    }

}

1.state这个对象内部可以是任意的数据类型
2.ajax请求是异步进行的,所以数据要在 componentWillMount或 componentDidMount生命周期内完成。
3.componentWillMount 内的this与ajax内的this不是一样的,需要进行绑定

var _this = this;
_this.setState({ posts });

项目比较大时,我们可以用redux,以上适用于小型项目哦,哈哈

萌萌哒

相关文章

  • Ajax请求的数据绑定给组件

    用了一天的时间搞这个,踩坑不少 1.state这个对象内部可以是任意的数据类型2.ajax请求是异步进行的,所以数...

  • React入门教程(9)Ajax与React的上下文

    ajax请求 react的组件中,一般我们在 componentDidMount事件中做ajax请求,并获得数据后...

  • JS一些基础操作

    Ajax请求数据 DOM 操作基础组件 获得checkbox状态 时间format

  • ajax

    Ajax 1 - 请求纯文本 Ajax 2 - 请求JSON数据 Ajax 3 - 请求Github接口 Ajax...

  • ajax请求接口参数

    如何使用ajax请求数据: // 请求接口数据$.ajax({ url: 'http://localhost/...

  • ajax

    特点 ajax ajax入门 ajax请求与发送数据 ajax工具类封装 type:请求类型url:请求地址dat...

  • 父子组件异步数据传递

    背景 很多时候,我们是存在这种场景的,父子组件之间传递的数据,是父组件ajax请求后返回的数据。 解决方案 在传递...

  • ajax与jsonp、jsonp

    轮播图 json 数据格式 ajax与jsonp ajax是获取数据的 get请求 post请求 url:"js/...

  • 原生js ajax网络数据请求 XMLHttprequest、A

    再学封装ajax请求 原生JS,AJAX数据封装 兼容性处理 脚本: 请求操作:

  • 父组件传值给子组件传值时报错

    在父组件传值给子组件时,会报出找不到属性的错 这是因为父组件传入给子组件的这个值,是由ajax请求的,当ajax请...

网友评论

      本文标题:Ajax请求的数据绑定给组件

      本文链接:https://www.haomeiwen.com/subject/kqnqwttx.html