2016-11-20 103 views
3

我正在尝试将Firebase与React-Native/Redux一起使用我需要在用户每次登录或注销时发送一个操作。我怎样才能从根组件发出一个动作?根组件的React/Redux调度操作?

class App extends Component { 
    componentWillMount() { 
     firebase.auth().onAuthStateChanged((user) => { 
      if (user) { 
      // Dispatch Action here 
      } else { 
      // Disptach Action here 
      } 
     }); 
    } 

    render() { 
     const store = createStore(reducers, {}, applyMiddleware(ReduxThunk)); 

     return (
      <Provider store={store}> 
       <Router /> 
      </Provider> 
     ); 
    } 
} 

export default App; 

回答

3
class App extends Component { 
    constructor() { 
     this.store = createStore(reducers, {}, applyMiddleware(ReduxThunk)); 
    } 

    componentWillMount() { 
     firebase.auth().onAuthStateChanged((user) => { 
      if (user) { 
       this.store.dispatch(...); 
      } else { 
       this.store.dispatch(...); 
      } 
     }); 
    } 

    render() { 
     return (
      <Provider store={this.store}> 
       <Router /> 
      </Provider> 
     ); 
    } 
} 

export default App; 

引用您的组件道具传递给它的行动,不使内render()功能任何副作用。它必须是纯粹的功能。

+0

最好不要在组件构造器中创建存储,而要使用React-Redux中的Provider。在组件内部创建存储不是Redux方式。 – DDS

+0

@DDS这是主要的应用程序组件,因此在构造函数或外部组件中初始化存储没有区别。 – farwayer

2

使用了Redux connectmapDispatchToProps ...查看说明书here。 Connect仍然可以与根组件一起工作。然后在你的componentWillMount您可以通过connect

+1

我已经试过这一点,它不工作我得到以下错误“找不到“存储”在“连接(应用)”的上下文或道具中。或者将根组件包装在中,或者将“存储”明确地传递给“连接(应用)” – Groovietunes

+0

将提供者移动到s tatic,并将您的身份验证内容放在使用连接的父组件上。 –

+0

我得到了同样的错误,我正在使用react-native-router-flux,可能与它有什么关系? – Groovietunes

0

我找到了解决这个问题的方法。不应该是最好的方式,但它的工作原理。

将您对根组件(App.js)设置loggedIn的身份验证请求设置为true或false。 (在下面的例子中,我使用了firebase身份验证)

完成后,您将状态作为通道传递给Component(InitialSetUp.js),然后您可以使用Redux设置状态。

在InitialSetUp上,您的行为像根,呈现应用程序本身。

以下你可以找到这个例子。

App.js

... 

const store = createStore(reducers, 
window.__REDUX_DEVTOOLS_EXTENSION__ && 
window.__REDUX_DEVTOOLS_EXTENSION__()); 

export default class App extends Component { 
state = { loggedIn: null}; 

componentWillMount() { 
firebase.initializeApp({ 
...YOUR SETUP 
}); 

firebase.auth().onAuthStateChanged((user) => { 
if (user) { 
this.setState({ loggedIn: true}); 
} else { 
this.setState({ loggedIn: false}); 
} 
}); 
} 

renderInitialView() { 
return <InitialSetUp loggedIn={this.state.loggedIn}/> 
} 

render() { 
return (
<Provider store={store}> 
<View style={styles.container}> 
{this.renderInitialView()} 
</View> 
</Provider> 
); 
} 
} 

InitialSetup.js

... 

class initialSetUp extends Component { 

renderInitialView() { 
this.props.setLogged(this.props.loggedIn); 
return <Navigation /> 
} 

render() { 
return (
<View style={styles.container}> 
{this.renderInitialView()} 
</View> 
); 
} 
} 

export default connect(null, actions)(initialSetUp); 

好运O/