本文介绍了React.js:使用Fetch API加载JSON数据,并从对象数组中加载道具的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完全没有新的react.js,在完成教程和阅读文档之后,我仍然在使用js fetch从JSON文件加载数据以及从对象数组设置属性方面苦苦挣扎。我也不确定我是否正在我的事件处理程序中正确访问DOM属性。我必须遗漏一些相当简单的东西。

Totally new to react.js and after going through the tutorial and reading the docs, I'm still struggling a bit with using js fetch to load my data from a JSON file as well as setting properties from an array of objects. I'm also not certain I'm accessing DOM properties correctly in my event handler. I must be missing something rather straightforward.

作为参考,和

ETA:我从文档中不知道babel浏览器已被弃用,因此决定只使用带有ES5语法的直接Javascript而不是JSX。代码在下面更新,但它仍然没有呈现标记。

ETA: I had no idea from the docs that babel browser was deprecated so decided to just use straight Javascript with ES5 syntax instead of JSX. Code updated below, but it's still not rendering the markup.

var CanvasAnimation = React.createClass({
    getInitialState: function() {
        return {data: []};
    },
    loadData: function() {
        /*
        fetch("data.json")
            .then(function(response) {
                return response.json
                    .then(function(json){
                        this.setState({data: json});
                    }.bind(this))
            }.bind(this));
        */
        const data = [
            { id: "stalkerOne", width: 225, height: 434, spriteSheetURL: 'spriteSheets/stalkerone.jpg', rows: 5, columns: 5, totalFrames: 24 },
            { id: "stalkerTwo", width: 175, height: 432, spriteSheetURL: 'spriteSheets/stalkertwo.jpg', rows: 6, columns: 5, totalFrames: 26 },
            { id: "stalkerThree", width: 251, height: 432, spriteSheetURL: 'spriteSheets/stalkerthree.jpg', rows: 6, columns: 5, totalFrames: 28 }
        ];
    },
    componentDidMount: function() {
        this.loadData();
    },
    componentDidUpdate: function() {
        function animation(json) {
            return json.map(function(data) {
                return(
                    new CanvasSprite(
                        document.getElementById(data.id),
                        data.width,
                        data.height,
                        data.spriteSheetURL,
                        data.rows,
                        data.columns,
                        data.totalFrames)
                );
            });
        };
        this.setState({animaton: animation(this.state.data)});
    },
    handleInteraction: function(event, index) {
        var offsetY = event.clientY - event.node.getBoundingClientRect().top;
        var relY = offsetY/this.state.data.height;
        this.props.animation[index].setFrame(relY);
    },
    render: function() {
        var canvases = this.state.data.map(function(data, index) {
            return (
                React.createElement('canvas',
                                    id = data.id,
                                    width = data.width,
                                    height = data.height,
                                    style = 'border:5px solid white',
                                    onMouseOver= this.handleInteraction(event, index))
            );
        });
        return(
            React.createElement('div', canvases)
        );
    }
});


ReactDOM.render(
    React.createElement(CanvasAnimation, null),
    document.getElementById('content')
); 

推荐答案

好.. 。得到了@gumingfeng和@hkal的帮助。

Ok... Here's the working project. Got some help from @gumingfeng and @hkal.

经验教训:


  1. React文档过时了。

  2. Straight JS vs. JSX实际上并不差错。

  3. 纠正了Fetch中的一些语法错误。

  4. 对象数组需要在加载数据后实例化以便在构造函数中传递DOM引用。

  5. 但是,调用 setState() inside componentDidUpdate()触发无限循环,因此必须直接设置对象数组并独立于状态。

  6. 从数组创建DOM元素时,React不会自动将事件处理程序分配给特定元素。换句话说,它必须传递数组索引,以便可以用来访问数组中的值。

  1. The React docs are ridiculously outdated.
  2. Straight JS vs. JSX is really no worse imo.
  3. Corrected some syntax errors in Fetch.
  4. Object array needs to be instantiated after data is loaded in order to pass DOM references in the constructors.
  5. However, calling setState() inside componentDidUpdate() triggers an infinite loop so had to set the object array directly and independently from state.
  6. When creating DOM elements from an array, React does not automatically assign the event handler to the particular element. In other words, it must be passed the array index so that can be used to access its values in the arrays.

哇,我认为就是这样。希望这有助于其他人。

Whew, I think that's it. Hope this helps others.

我最后会说,给React一个没有JSX的尝试。这真的不是那么糟糕:)

And I would just conclude by saying, give React a try without JSX. It's really not that bad :)

const { Component } = React;
const { render } = ReactDOM;

class CanvasAnimation extends Component {

    constructor(){
        super();
        this.state = {
            data: []
        };
    };

    componentDidMount() {
        fetch("data.json")
            .then( (response) => {
                return response.json() })
                    .then( (json) => {
                        this.setState({data: json});
                    });
    };

    componentDidUpdate() {
        function animation(json) {
            return json.map( (data) => {
                return(
                    new CanvasSprite(
                        document.getElementById(data.id),
                        data.width,
                        data.height,
                        data.spriteSheetURL,
                        data.rows,
                        data.columns,
                        data.totalFrames)
                );
            });
        };
        //this.setState({animation: animation(this.state.data)}); //causes infinite loop
        this.animation = animation(this.state.data);
    };

    handleInteraction(event, index) {
        var offsetY = event.clientY -  document.getElementById(this.state.data[index].id).getBoundingClientRect().top;
        var relY = offsetY/this.state.data[index].height;
        this.animation[index].setFrame(relY);
    };

    render() {
        var canvases = this.state.data.map( (data, index) => {
            return (
                React.createElement('canvas',
                                    {id : data.id,
                                    width : data.width,
                                    height : data.height,
                                    //style : {border: '5px solid white'},
                                    onMouseMove : (event) => this.handleInteraction(event, index)}
                                    )
            );
        });
        return(
            React.createElement('div', null, ...canvases)
        );
    };

};


render(
    React.createElement(CanvasAnimation, null),
    document.getElementById('content')
);

这篇关于React.js:使用Fetch API加载JSON数据,并从对象数组中加载道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 14:48