【问题标题】:How can I change the reflux listenTo mixin based on a prop in a react.js component如何根据 react.js 组件中的道具更改回流listenTo mixin
【发布时间】:2016-07-29 16:07:16
【问题描述】:

谁能帮忙解决这个问题...

我有这个列表组件,我希望能够切换不同的数据存储(在 props 中定义)

mixins:[Reflux.listenTo(RecentPupilsStore, 'onChange')],

但我想这样做 -

mixins:[Reflux.listenTo(this.props.store, 'onChange')],

但在 mixin 中似乎没有可用的道具。我也尝试将其转移到函数中:

mixins:[Reflux.listenTo(this.setStore(this.props.store), 'onChange')],
setStore: function(store){
    if(store == 'RecentPupilsStore') { return RecentPupilsStore; }
},

任何帮助表示赞赏。相当新的 ot 反应,但试图使其尽可能可重用!

EG:我想包含这样的组件:

<FilterList data="pupils" />
<FilterList data="groups" />

等 - 这些会查看这些商店。

【问题讨论】:

    标签: reactjs jsx refluxjs


    【解决方案1】:

    我不会说这是最好的解决方案,但它回答了您关于如何使用道具定义要收听的商店名称的问题。

    您不需要定义应用 Mixin 的商店和方法。您可以使用更通用的 'Reflux.ListenerMixin' 并将其与在 'ComponentDidMount' 中的监听器注册相结合。

    var MyComponent = React.createClass({
        mixins: [Reflux.ListenerMixin],
        // Lifecycle events
        componentDidMount: function() {
            var theStore = defineTheStore(this.props.data);
            this.listenTo(theStore, this.onChange);
        },
        render: function() {
            return(
                <div >
                    ....
                </div>
            );
        },
        onChange: function() {
    
        }
    });
    

    【讨论】:

    • 感谢 Björn,这与我最终解决的方式类似 :) 感谢您的回复。
    【解决方案2】:

    我会继续使用 mixin,只听两个商店并相应地映射您的数据。

    componentDidMount = () => {
        // console.log('AppCtrl componentDidMount');
        this.unsubscribeApp = AppStore.listen(this.appStoreDidChange);
        this.unsubscribeGS = GenusSpeciesStore.listen(this.gsStoreDidChange);
    };
    componentWillUnmount = () => {
        this.unsubscribeApp();
        this.unsubscribeGS();
    };
    appStoreDidChange = () => {
        this.setState(getAppState());
    };
    gsStoreDidChange = () => {
        this.setState(getGsState());
    };
    

    【讨论】:

    • 感谢@J Mark Stevens 的回复 - 抱歉,可能是我的解释,但我一次只想看一家商店 - 这只会在页面之间发生变化。因此,Pupils 页面将提供 /pupils 数据,Groups 页面将提供 /groups 数据。它只是可重用的组件。我想像这样初始化组件:&lt;List data="pupils" /&gt; 这将监视瞳孔存储。
    • 道歉@J。马克史蒂文斯我误读了你的代码。我知道你现在在做什么 - 我现在已经关注了这个和这个 github.com/reflux/refluxjs#user-content-react-component-example 并看到监听操作可以进入 componentDidMount() - 感谢标记为正确:)
    猜你喜欢
    • 1970-01-01
    • 2021-10-20
    • 2020-12-21
    • 2018-12-07
    • 2020-04-11
    • 2019-07-01
    • 2016-02-04
    • 2018-05-09
    • 2015-09-29
    相关资源
    最近更新 更多