从根组件传递信息(React Native,Redux,React Navigation和Push Notifications)

时间:2018-02-22 21:38:48

标签: reactjs react-native redux react-redux react-navigation

在我的主App.js中,我使用React Navigation连接组件(' Setup')并运行: const ReduxNavigator = connect(Setup)

然后我将这个ReduxNavigator组件放入我的主App组件中。这将使用Redux连接React Navigation。

我现在正在设置推送通知。这需要将一堆侦听器组件放到根组件上(根组件可以工作)。

如何处理侦听器提供的信息,将其作为道具传递或将其传递给全局状态,以便我的应用程序的其余部分可以访问它?我也可能想要基于这些听众进行导航(例如,打开推送通知)。我该怎么做?

以下是我的代码的简化示例:

import React, { Component } from 'react';
import { Provider, connect } from 'react-redux'
import { addNavigationHelpers } from 'react-navigation';
import OneSignal from 'react-native-onesignal';

import Navigator from './src/Navigator'
import configureStore from './src/store/configureStore';

const { store } = configureStore() 

class Setup extends Component {
    componentDidMount() {
        OneSignal.addEventListener('opened', this.onOpened);
    }

    onOpened(openResult) {
      // where do I pass this information?
      // this.setState() doesn't workk
    }

    render() {
        return(
            <Navigator 
                navigation={addNavigationHelpers({
                dispatch: this.props.dispatch,
                state: this.props.nav,
            })} />
        )
    }
}

const mapStateToProps = (state) => ({
    nav: state.nav
});

const ReduxNavigator = connect(mapStateToProps,  { /* importing actions here doesn't work */ })(Setup);

export default class App extends Component {    
    render() {
        return (
            <Provider store={store}>
                <ReduxNavigator/>
            </Provider>
        );
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

我找到了一种在App根组件中访问调度的方法。首先将侦听器和组件生命周期事件移动到App组件...

componentWillMount() {
        this.store = store // <--- add this
        OneSignal.addEventListener('opened', this.onOpened);
}

onOpened = (openResult) => { // <--- make this is an arrow function 
      this.store.dispatch({type: "set_value", payload: "hello"}) // <--- dispatch stuff to your reducers
}

另外,改变&#34;存储&#34; to&#34; this.store&#34;在提供者中:

<Provider store={this.store}>

希望帮助某人(并希望它不是不好的做法......)