ajax 请求完成后更新 reactjs 上下文

update reactjs context after ajax request finished with flux architecture

我需要在 ajax 请求完成后更新上下文。我正在使用 flux 架构,一切正常,当我的组件收到更新通知时,我需要设置新的上下文。

简单演示:

我有一个 parent 组件,它通过调用存储来生成上下文。商店在其他地方初始化 ajax 请求后获取数据。像这样:

RowAPI.ajaxGetAllRows();

然后我有了包含上下文的组件:

let ParentComponent = React.createClass({

    childContextTypes: {
        rows: React.PropTypes.object
    },

    getChildContext: function() {
        return {
            rows: RowStore.getAllRows(),
        };
    },

    componentDidMount: function() {
        RowStore.addChangeListener(this._onRowsChanged);
    },

    componentWillUnmount: function() {
        RowStore.removeChangeListener(this._onRowsChanged);
    },


    render() {

        return (
            <ChildComponent />
        );
    },

    _onRowsChanged: function() {
        //Now we need to update context
    }

});

现在,由于我们正在侦听行更改,我们将在 ajax 请求完成时获得更新并将数据放入我们的存储中。现在我们需要获取该数据并将其设置为上下文。就是这个问题。

这是我的 child 使用上下文的组件。我知道我可以将行作为道具传递给我的 child 但这只是一个例子,在我的真实场景中我有很多 children 需要传递道具。

let ChildComponent = React.createClass({

    contextTypes: {
        rows: React.PropTypes.object
    },


    render() {

        return (
            <div style={styles.wrapper}>
                {this.context.rows}
            </div>
        );

    },

});

提前致谢!

我会更改 ParentComponent 中的 getChildContext 以引用状态而不是对 RowStore 的函数调用。

 getChildContext: function() {
        return {
            rows: this.state.rows,
        };
    }

然后,每当一行发生变化时,它会调用 _onRowsChanged 回调,它可以相应地设置 this.state.rows。

我认为在 getChildContext 中调用 RowStore.getAllRows() 的原始方法的问题在于它只被调用了一次。没有什么会迫使它在每次更改时调用 RowStore.getAllRows() 。

但是,通过使用状态,您可以使用 Flux 概念 "force" 每次更新时状态发生变化,这将反映在上下文中。