【问题标题】:React, Redux, Logout action doesn't update componentsReact、Redux、Logout 操作不会更新组件
【发布时间】:2018-04-08 01:00:44
【问题描述】:

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

而且我无法解释为什么它在注销时不起作用。

我按照教程学习了 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 };
}

【问题讨论】:

  • “它不工作”不是很有帮助。您具体预计会发生什么,具体会发生什么?

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


【解决方案1】:

编辑

您没有将logoutAction 传递给connect(),您应该将其命名为this.props.logoutAction()

您的导航栏应如下所示:

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);

【讨论】:

  • 你的意思是在另一个问题上发布这个?
  • 亚历山大很好用。你能解释一下为什么它现在可以工作吗?请...
  • @JohnSam 已编辑
  • 好的,但是为什么我在代码中需要onLogout 而不是简单的() =&gt; { this.props.logoutAction(this.props.history)
  • @JohnSam 两种方式都可以,我更喜欢onLogout
猜你喜欢
  • 2021-11-15
  • 2019-08-18
  • 2018-04-22
  • 2016-06-30
  • 2022-08-17
  • 1970-01-01
  • 2021-10-23
  • 1970-01-01
  • 2017-06-10
相关资源
最近更新 更多