javascript [Redux示例] #react #redux

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript [Redux示例] #react #redux相关的知识,希望对你有一定的参考价值。

// UI ACTIONS
export const TOGGLE_MODAL_VISIBILITY = "TOGGLE_MODAL_VISIBILTIY";

// EMOJI ACTIONS
export const SELECT_DATE = "SELECT_DATE";
export const SELECT_EMOJI = "SELECT_EMOJI";

// USER ACTIONS
export const LOG_IN = "LOG_IN";
export const LOG_OUT = "LOG_OUT";
import React, { Component } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as userActions from "../actions/userActions";

import { app, authProvider, auth } from "../constants/firebase";

import TopMenuBar from "../components/TopMenuBar";

class AuthContainer extends Component {
  static propTypes = {
    // prop: PropTypes
  };

  componentDidMount = () => {
    auth.onAuthStateChanged(user => {
      if (user) {
        this.setState({ user });
        this.props.userActions.logIn(user);
      }
    });
  };

  logIn = user => {
    auth.signInWithPopup(authProvider).then(result => {
      const user = result.user;
      this.setState({
        user
      });
      this.props.userActions.logIn(user);
    });
  };

  logOut = () => {
    auth.signOut().then(() => {
      this.setState({
        user: null
      });
      this.props.userActions.logOut();
    });
  };

  render() {
    return (
      <div>
        <TopMenuBar
          auth={this.props.auth}
          logIn={this.logIn}
          logOut={this.logOut}
        />
      </div>
    );
  }
}

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

const mapDispatchToProps = dispatch => {
  return {
    userActions: bindActionCreators(userActions, dispatch)
  };
};

const withRedux = connect(
  mapStateToProps,
  mapDispatchToProps
)(AuthContainer);

export default withRedux;
import { combineReducers } from "redux";
import uiReducer from "./uiReducer";
import emojiReducer from "./emojiReducer";
import userReducer from "./userReducer";

const rootReducer = combineReducers({
  ui: uiReducer,
  emoji: emojiReducer,
  auth: userReducer
});

export default rootReducer;
import { createStore, compose, applyMiddleware } from "redux";
import rootReducer from "../reducers";
import reduxImmutableStateInvariant from "redux-immutable-state-invariant";
import createHistory from "history/createBrowserHistory";
import thunk from "redux-thunk";
import { connectRouter, routerMiddleware } from "connected-react-router";

export const history = createHistory();
const connectRouterHistory = connectRouter(history);

function configureStoreProd(initialState) {
  const reactRouterMiddleware = routerMiddleware(history);
  const middlewares = [
    // Add other middleware on this line...

    // thunk middleware can also accept an extra argument to be passed to each thunk action
    // https://github.com/reduxjs/redux-thunk#injecting-a-custom-argument
    thunk,
    reactRouterMiddleware
  ];

  return createStore(
    connectRouterHistory(rootReducer),
    compose(applyMiddleware(...middlewares))
  );
}

function configureStoreDev(initialState) {
  const reactRouterMiddleware = routerMiddleware(history);
  const middlewares = [
    // Add other middleware on this line...

    // Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches.
    reduxImmutableStateInvariant(),

    // thunk middleware can also accept an extra argument to be passed to each thunk action
    // https://github.com/reduxjs/redux-thunk#injecting-a-custom-argument
    thunk,
    reactRouterMiddleware
  ];

  const composeEnhancers =
    window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools
  const store = createStore(
    connectRouterHistory(rootReducer),
    composeEnhancers(applyMiddleware(...middlewares))
  );

  // if (module.hot) {
  //   // Enable Webpack hot module replacement for reducers
  //   module.hot.accept("../reducers", () => {
  //     const nextRootReducer = require("../reducers").default; // eslint-disable-line global-require
  //     store.replaceReducer(connectRouterHistory(nextRootReducer));
  //   });
  // }

  return store;
}

const configureStore =
  process.env.NODE_ENV === "production"
    ? configureStoreProd
    : configureStoreDev;

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

export default configureStore;
import * as types from "../constants/actionTypes";

export const logIn = user => ({
  type: types.LOG_IN,
  user
});

export const logOut = () => ({
  type: types.LOG_OUT
});
import { LOG_IN, LOG_OUT } from "../constants/actionTypes";

const initialState = {
  user: null
};

export default (state = initialState, action) => {
  switch (action.type) {
    case LOG_IN:
      let { uid, displayName, photoURL, email } = action.user;
      return { ...state, user: { uid, displayName, photoURL, email } };
    case LOG_OUT:
      return { ...state, user: null };
    default:
      return state;
  }
};
import React from "react";
import { app, authProvider, auth } from "../constants/firebase";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import * as userActions from "../actions/userActions";

function WithAuth(WrappedComponent) {
  return class extends React.Component {
    state = {
      user: null
    };

    componentDidMount = () => {
      console.log("mounted", this.props);
      auth.onAuthStateChanged(user => {
        if (user) {
          this.setState({ user });
        }
        console.log("user", user);
        // this.props.logIn(user);
      });
    };

    logIn = user => {
      auth.signInWithPopup(authProvider).then(result => {
        const user = result.user;
        this.setState({
          user
        });
        // this.props.logIn(user);
        console.log(user);
      });
    };

    logOut = () => {
      auth.signOut().then(() => {
        this.setState({
          user: null
        });
        console.log("log out");
      });
    };

    render() {
      // Wraps the input component in a container, without mutating it. Good!
      return (
        <WrappedComponent
          logIn={this.logIn}
          logOut={this.logOut}
          user={this.state.user}
          {...this.props}
        />
      );
    }
  };
}

export default WithAuth;

以上是关于javascript [Redux示例] #react #redux的主要内容,如果未能解决你的问题,请参考以下文章

javascript Webpack React / Redux热模块重新加载(HMR)示例

React Native - Redux 不会立即更新

[Redux/Mobx] 什么是redux?说说你对redux的理解?有哪些运用场景?

React,redux 组件不会在路由更改时更新

Redux 连接函数说明

减速器没有被触发(redux-promise with axios)