React,Redux,Logout操作不会更新组件

时间:2017-10-26 15:05:09

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

我有这个:https://codesandbox.io/s/j3llymyxqw

我无法解释为什么它没有在Logout上工作。

我按照教程学习react-redux这样做的方法。

为什么它不起作用?

authReducers.js

import {
  AUTHENTICATED,
  UNAUTHENTICATED,
  AUTHENTICATION_ERROR
} from "../actions/actionTypes";

export default function(state = {}, action) {
  switch (action.type) {
    case AUTHENTICATED:
      return { ...state, authenticated: true };

    case UNAUTHENTICATED:
      return { ...state, authenticated: false };

    default:
      return state;
  }
}

authActions.js

import * as actionTypes from "./actionTypes";

export function loginAction(history) {
  return async dispatch => {
    const timeout = ms => new Promise(res => setTimeout(res, ms));
    await timeout(1000);
    ....
    dispatch({ type: actionTypes.AUTHENTICATED });
  };
}

export function logoutAction(history) {
  ...
  return { type: actionTypes.UNAUTHENTICATED };
}

1 个答案:

答案 0 :(得分:0)

修改

您没有将logoutAction传递给connect()而您应该将其称为this.props.logoutAction()

您的NavBar应如下所示:

import React, { Component } from "react";
import { connect } from "react-redux";
import { Link, NavLink } from "react-router-dom";

import { logoutAction } from "./actions/authActions";

class Navbar extends Component {

  onLogout = () => {
    this.props.logoutAction(this.props.history)
  }

  render() {
    if (this.props.authenticated) {
      return (
        <div>
          <div>
            <Link to="/">Home</Link>
            {" | "}
            <NavLink to="/about">About</NavLink>
            {" | "}
            <NavLink to="/faq">Faq</NavLink>
            {" | "}
            <button onClick={this.onLogout}>
              Sign out
            </button>
          </div>
          <br />
          <br />
        </div>
      );
    }
    return (
      <div>
        <NavLink to="/login">Log in</NavLink>
        <br />
        <br />
      </div>
    );
  }
}

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

export default connect(mapStateToProps, {
  logoutAction
})(Navbar);