简体   繁体   中英

How to handle data changes in Flux/React?

So far I worked quite thoroughly through the two official Flux architecture examples ( https://github.com/facebook/flux ).

However, I am really unsure of how you would accomplish a change of data after the initial data has been rendered.

For instance, imagine a todo item changes in the example because of a server response, how would that be implemented to have the according item updating correctly without using setProps() in the item component (which is, as far as I understood, prohibited)?

This might be more of React-related misunderstanding - looking forward to your suggestions!

The idea with flux is that you set your React component's internal state (or part of it) to an object or value from a store every time that store changes.

So for example something like this (not real code, but to give you an idea):

var Component = react.createClass({
    getInitialState: function() {
        return { 
            items: Flux.getStore("ItemStore").getItems()
        }
    },

    componentDidMount: function() {
        this.store = Flux.getStore("ItemStore");
        this.store.addChangeListener(this.onStoreChange)
    },

    componentWillUnmount: function() {
        this.store.removeChangeListener(this.onStoreChange);
    },

    onStoreChange: function() {
        this.setState({
            items: this.store.getItems()
        });
    },

    render: function() {

        var items = [];
        for (var i = 0; i < this.state.items; i++) {
            items.push(
                <li key={i}>{this.state.items[i]}</li>
            );
        }

        return (
            <ul>{items}</ul>
        );
    }
});

What this example component does is render a list of this.state.items that reside in a store called ItemStore and are accessed by ItemStore.getItems() . So take a look at the componentDidMount which gets the store, binds a callback to whenever the store is changed onStoreChange and then sets the current component state of items to the items array provided by store.getItems() .

As a result when the component is first mounted it gets the current items from the store and displays them, whenever the store changes it will execute onStoreChange which gets the items again from the store and sets them again via this.setState() .

Naturally we want to be clean so this component also removes the onStoreChange binding when the component is being unmounted.

Note: Remember that calling this.setState() inside componentDidMount does not cause a component re-render :)

More on this in the facebook-flux documentation here: http://facebook.github.io/flux/docs/todo-list.html#listening-to-changes-with-a-controller-view

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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