如何使用react - 在redux中的路由器

时间:2018-03-08 08:29:32

标签: javascript reactjs react-router react-redux react-router-v4

import React, { Component } from "react";
import { connect } from "react-redux";   
import { Link } from "react-router-dom";
import { userChange, passwordChanged, islogin } from "./actions";

class Login extends Component {
    constructor(props) {
        super(props);
        this.login = this.login.bind(this);
        this.handleUserChange = this.handleUserChange.bind(this);
        this.handlePasswordChange = this.handlePasswordChange.bind(this);
    }
    handlePasswordChange(text) {
        this.props.passwordChanged(text.target.value);
    }
    handleUserChange(text) {
        this.props.userChange(text.target.value);
    }
    login() {
        const { username, password } = this.props;
        this.props.islogin({ username, password });
    }
    componentWillUpdate() {}


render (){
return (.........)}
    }
    const mapStateToProps = ({ authRed }) => {
        const { username, password, navigate } = authRed;
        return { username, password, navigate };
    };
    export default connect(mapStateToProps, {
        userChange,
        passwordChanged,
        islogin
    })(Login);

以上是登录页面我有一个函数是登录,它接受参数并将其推送到操作 在action.js

export const userChange = text => {
    return {
        type: "USER_CHANGED",
        payload: text
    };
};
export const passwordChanged = text => {
    return {
        type: "PASSWORD_CHANGED",
        payload: text
    };
};
export const islogin = ({ username, password }) => {
    return dispatch => {
        if (username !== "" && password !== "") {
            localStorage.setItem("Loggedin", true);
            dispatch({ type: "NAVIGATE" });
        } else {
            console.log("is empty");
        }
    };
};

我想使用this.props.history.push()但它在reducer中既不起作用也不起作用 我该怎么做才能做这个工作

2 个答案:

答案 0 :(得分:1)

您可以从app.js文件中导出历史记录:

// Create redux store with history
const initialState = {};
const history = createHistory();
const store = configureStore(initialState, history);
export { history };

然后在您的操作中,您可以创建如下函数:

import { history } from 'app';

function forwardTo(location) {
  history.push(location);     
}

答案 1 :(得分:0)

在我看来,你有两种选择。从redux存储区返回一些标志到Component,然后重定向。或者使用react-router-redux