我创建了一个应用程序,一切正常,但是当我移动路线或重新加载页面时,状态恢复为默认状态,也许我可以使用库作为react-persist来解决此问题,或者找到某种方式放置在本地存储上声明,我认为这种方法不是最好的方法。也许您是另一种选择?
❓ FAQ/Wiki: https://github.com/JamesIves/github-pages-deploy-action/wiki
? Support: https://github.com/JamesIves/github-pages-deploy-action/issues
⭐ Contribute: https://github.com/JamesIves/github-pages-deploy-action/blob/dev/CONTRIBUTING.md
Maintained by James Ives (https://jamesiv.es)
Checking configuration and starting deployment… ?
Deploying using …… ?
Configuring git…
/usr/bin/git init
Reinitialized existing Git repository in /home/runner/work/FirstBlazor/FirstBlazor/.git/
/usr/bin/git config user.name ngaisteve1
/usr/bin/git config user.email xxx@gmail.com
/usr/bin/git remote rm origin
/usr/bin/git remote add origin ***github.com/ngaisteve1/FirstBlazor.git
/usr/bin/git fetch --no-recurse-submodules
From https://github.com/ngaisteve1/FirstBlazor
* [new branch] master -> origin/master
Git configured… ?
Starting to commit changes…
/usr/bin/git ls-remote --heads ***github.com/ngaisteve1/FirstBlazor.git master | wc -l
136e7850750d3861e72a15355289952f94777c9b refs/heads/master
/usr/bin/git checkout --progress --force development
error: pathspec 'development' did not match any file(s) known to git
Running post deployment cleanup jobs… ?️
/usr/bin/git worktree remove github-pages-deploy-action-temp-deployment-folder --force
fatal: 'github-pages-deploy-action-temp-deployment-folder' is not a working tree
##[error]The process '/usr/bin/git' failed with exit code 128
Deployment failed! ❌
`store.js`
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import rootReducer from "./reducer/rootReducer";
const initialState = {};
export default createStore(rootReducer, initialState, applyMiddleware(thunk));
`reducer`
import {
REGISTER_USER,
REGISTER_FAIL,
LOGIN_USER,
LOGIN_FAIL,
// LOAD_USER,
// LOAD_USER_FAIL,
// LOGOUT_USER,
} from "../constants";
const initialState = {
user: null,
loading: true,
isAuthenticated: false,
error: null,
};
export default (state = initialState, action) => {
switch (action.type) {
case REGISTER_USER:
return {
...state,
user: action.payload,
loading: false,
isAuthenticated: true,
error: null,
};
case REGISTER_FAIL:
return {
...state,
user: null,
loading: true,
isAuthenticated: false,
error: action.payload,
};
case LOGIN_USER:
localStorage.setItem("token", action.payload.token);
return {
...state,
user: action.payload,
loading: false,
isAuthenticated: true,
error: null,
};
case LOGIN_FAIL:
return {
...state,
user: null,
loading: true,
isAuthenticated: false,
error: action.payload,
};
default:
return state;
}
};
`Login`
import React, { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Redirect, useHistory } from "react-router-dom";
import { loginAction } from "../actions/loginAction";
const Login = () => {
const dispatch = useDispatch();
const data = useSelector((state) => state.auth);
let history = useHistory();
const [msg, setMsg] = useState("");
const [state, setState] = useState({
email: "",
password: "",
});
useEffect(() => {
let interval;
if (data.error) {
setMsg(data.error.msg);
interval = setTimeout(() => {
setMsg("");
}, 1000);
}
if (data.user) {
setMsg(data.user.msg);
interval = setTimeout(() => {
setMsg("");
}, 1000);
}
return () => {
clearTimeout(interval);
};
}, [data]);
const handleSubmit = (e) => {
e.preventDefault();
dispatch(loginAction(state));
};
const handleChange = (e) => {
setState({ ...state, [e.target.name]: e.target.value });
};
if (data.isAuthenticated) {
history.push("/dashboard");
}
console.log(data);
return (
<>
<span>{msg}</span>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<input name="email" onChange={handleChange} value={state.email} />
<input name="password" onChange={handleChange} value={state.password} />
<input type="submit" value="Login" />
</form>
</>
);
};
export default Login;
register
答案 0 :(得分:0)
您应该将令牌存储在本地存储中,然后将其取出并在重新加载时进行验证。另外,您应该执行新操作以从该令牌加载用户。每次重载时,状态将始终重置为初始状态。 我看不到您的registerAction页面,但loadUser应该是这样的
// Load User
export const loadUser = () => async (dispatch) => {
try {
const res = await axios.get('/api/auth');
dispatch({
type: USER_LOADED,
payload: res.data,
} catch (err) {
dispatch({
type: AUTH_ERROR,
payload: err.response.data,
});
}
};
/ api / auth就是这样
// @route GET api/auth
// @desc Get logged in user (Login)
// @access Private
router.get('/', auth, async (req, res) => {
try {
const user = await Planner.findById(req.user.id).select('-password');
if (user.type === 'Admin') {
res.json({ user, admin: true });
} else {
res.json({ user, admin: false });
}
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
例如,您需要使用jwttoken作为身份验证中间件 中间件文件就是这样
const jwt = require('jsonwebtoken');
const config = require('config');
module.exports = function (req, res, next) {
//Get token from header
const token = req.header('x-auth-token');
// Check if not token
if (!token) {
return res.status(401).json({ msg: 'No token, authorization denied' });
}
try {
const decoded = jwt.verify(token, config.get('jwtSecret'));
req.user = decoded.user;
next();
} catch (err) {
res.status(401).json({ msg: 'Token is not valid' });
}
};
我已经实现了Brad Travery的contact keeper项目的类似还原 您可以在此处查看完整的代码,确定会有所帮助 https://github.com/madaher-dev/contact-keeper 享受