reactjs - React/Redux 从根组件调度操作?

标签 reactjs firebase react-native redux firebase-authentication

我正在尝试将 firebase 与 React-Native/Redux 结合使用,我需要在每次用户登录或注销时调度一个操作。如何从根组件分派(dispatch)操作?

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;

最佳答案

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() 函数中产生任何副作用。它必须是纯函数。

关于reactjs - React/Redux 从根组件调度操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40699799/

相关文章:

node.js - 个人资料图片 uploader 的这种逻辑是否可扩展?

javascript - firestore 检查 id 是否存在于 id 数组中

android - 如何只为 Android 初始化 react-native 项目?

ios - react native iOS : Could not build module 'yoga' : 'algorithm' file not found

javascript - react axios 401未经授权

javascript - 如何在客户端对字符串进行 ESlint?

json - 组的 Firebase 数据库规则

javascript - 如何在 map 上创建一个覆盖标记,它保持在 react-native 的屏幕中心

javascript - React - 箭头函数错误(提案类字段)

javascript - 无法从 react-router-modal 访问历史记录