简体   繁体   中英

how to use react - router in redux

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

the above is the login page i have a function is login that takes the param and push it to the action in the 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");
        }
    };
};

i want to use this.props.history.push() but it doesnt work neither in the reducer neither in action how should i need to do this job

You can export the history in from your app.js file:

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

Then in your action you can create a function like the following:

import { history } from 'app';

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

In my opinion you have two options. Either return some flag from redux store to Component and then redirect. Or use react-router-redux

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM