简体   繁体   English

反应:将数组对象存储在状态中并使用键显示

[英]React: store array objects in state and display with keys

I'm learning react and I want to know the correct way to store object arrays in state and then access them later, or if it is correct and if I should do this at all. 我正在学习反应,我想知道在状态中存储对象数组,然后在以后访问它们的正确方法,或者是否正确以及是否应该这样做。

In react I perform and AJAX request and I get a list of objects. 在反应中,我执行AJAX请求,并得到对象列表。 These I want to store in state so that I can push it to another react class as a props. 我想将它们存储在状态中,以便可以将其作为道具推送到另一个React类。 I want to be able to access the items in the objects. 我希望能够访问对象中的项目。

UPDATE - fixed and working 更新 -已修复且正在运行

var Providers = React.createClass({

    getInitialState: function() {
        return {providers: []};
    },

    componentDidMount: function () {
        var uri = this.props.source;

        $.ajax({
            type: "GET",
            dataType: 'json',
            url: uri,
            crossDomain: true,
        })
        .done(function (data) {
            var newProviders = []
            $.each(data, function (i, p) {
                newProviders.push(data[i]);
            });
            console.log(newProviders);
            this.setState({ providers: newProviders });

        }.bind(this))
        .fail(function (xhr, textStatus, errorThrown) {
            console.log(xhr.responseText);
            console.log(textStatus);
        });
    },

    render: function () {
        return (
            <div>
                <Provider providers={this.state.providers}></Provider>
            </div>
        );
    }
});

var Provider = React.createClass({
    componentDidUpdate: function () {
        console.log(this.props.providers[0]);
    },

    render: function () {
        return (
            <p></p>
        );
    }
});

Your code is most likely working, but I suspect that your understanding of componentDidMount is incorrect. 您的代码很可能正常工作,但我怀疑您对componentDidMount的理解不正确。 componentDidMount is called only once, after the component is initially rendered. componentDidMount只调用一次,之后组件最初呈现。 It is not called when props are updated. 道具更新时不调用。

You may want to look into componentDidUpdate . 您可能需要研究componentDidUpdate

In general, I would avoid using custom objects for state - especially shared mutable objects - and use plain objects instead. 通常,我会避免使用状态的自定义对象(尤其是共享的可变对象),而应使用普通对象。

I wouldn't setState with each element in array because it will do one terrible thing - rerender component each time. 我不会对数组中的每个元素设置setState,因为它会做一件可怕的事情-每次都重新渲染组件。 Which will result in terrible performance later id it will become big app. 稍后将导致可怕的性能,它将成为大型应用程序。

I would suggest to setState already prepared data so it wouldnt needlesly rerender [i] Times. 我建议setState已经准备好数据,这样就不会轻易重新渲染[i] Times。 So setState only once in Ajax requests if you can 因此,如果可以的话,setState在Ajax请求中仅一次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM