简体   繁体   English

React-Redux:在 JSX 中访问调度类型

[英]React-Redux: Access dispatch type in JSX

I have a login system with React-Redux and I want to display JSX when a specific dispatch Type is send.我有一个带有 React-Redux 的登录系统,我想在发送特定的调度类型时显示 JSX。
For example when the login system failed the dispatch type is LOGIN_FAIL and I want to display an error message but when the authentication is successful then the dispatch type is LOGIN_SUCCESS and I want to display a success message.例如,当登录系统失败时,调度类型为LOGIN_FAIL并且我想显示错误消息,但是当身份验证成功时调度类型为LOGIN_SUCCESS并且我想显示成功消息。 I already access the username trough mapStateToProps but I was curious if there is another way trough the dispatch type to do conditional rendering?我已经通过 mapStateToProps 访问了用户名,但我很好奇是否有另一种通过调度类型进行条件渲染的方法?
Thanks for your advice or tips on that topic.感谢您提供有关该主题的建议或提示。

This is my actions.js:这是我的 actions.js:

export const login = (email, password) => async dispatch => {
    const config = {
        headers: {
            'Content-Type': 'application/json'
        }
    };

    const body = JSON.stringify({ email, password });

    try {
        const res = await axios.post(`${process.env.REACT_APP_API_URL}/auth/jwt/create/`, body, config);

        dispatch({
            type: LOGIN_SUCCESS,
            payload: res.data
        });

        dispatch(load_user());
    } catch (err) {
        dispatch({
            type: LOGIN_FAIL
        });
    }
};

When i do user authentication, and i want to conditially render a component.当我进行用户身份验证时,我想有条件地呈现一个组件。 I use React routing dom.我使用 React 路由 dom。 This way i can create a PrivateRoute that will render the individual component out and redirect if the user !isAuthenticated.通过这种方式,我可以创建一个 PrivateRoute,如果用户 !isAuthenticated,它将呈现单个组件并重定向。 Check this out /看一下这个 /

https://blog.bitsrc.io/build-a-login-auth-app-with-mern-stack-part-1-c405048e3669 https://blog.bitsrc.io/build-a-login-auth-app-with-mern-stack-part-1-c405048e3669

This is the tutorial that you can clone the git这是你可以克隆git的教程

Private Route:私人路线:

 import React from "react"; import { Route, Redirect } from "react-router-dom"; import { connect } from "react-redux"; import PropTypes from "prop-types"; const PrivateRoute = ({ component: Component, auth, ...rest }) => ( <Route {...rest} render={props => auth.isAuthenticated === true ? ( <Component {...props} /> ) : ( <Redirect to="/login" /> ) } /> ); PrivateRoute.propTypes = { auth: PropTypes.object.isRequired }; const mapStateToProps = state => ({ auth: state.auth }); export default connect(mapStateToProps)(PrivateRoute);

MAIN APP:主应用程序:

 import React, { Component } from "react"; import { BrowserRouter as Router, Route, Switch } from "react-router-dom"; import jwt_decode from "jwt-decode"; import setAuthToken from "./utils/setAuthToken"; import { setCurrentUser, logoutUser } from "./actions/authActions"; import { Provider } from "react-redux"; import store from "./store"; import Navbar from "./components/layout/Navbar"; import Landing from "./components/layout/Landing"; import Register from "./components/auth/Register"; import Login from "./components/auth/Login"; import PrivateRoute from "./components/private-route/PrivateRoute"; import Dashboard from "./components/dashboard/Dashboard"; import "./App.css"; // Check for token to keep user logged in if (localStorage.jwtToken) { // Set auth token header auth const token = localStorage.jwtToken; setAuthToken(token); // Decode token and get user info and exp const decoded = jwt_decode(token); // Set user and isAuthenticated store.dispatch(setCurrentUser(decoded)); // Check for expired token const currentTime = Date.now() / 1000; // to get in milliseconds if (decoded.exp < currentTime) { // Logout user store.dispatch(logoutUser()); // Redirect to login window.location.href = "./login"; } } class App extends Component { render() { return ( <Provider store={store}> <Router> <div className="App"> <Navbar /> <Route exact path="/" component={Landing} /> <Route exact path="/register" component={Register} /> <Route exact path="/login" component={Login} /> <Switch> <PrivateRoute exact path="/dashboard" component={Dashboard} /> </Switch> </div> </Router> </Provider> ); } } export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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