【发布时间】:2021-08-12 09:04:50
【问题描述】:
我是 redux 的新手。 我要做的是从redux状态获取身份验证状态,如果身份验证为真,相应地渲染我的组件然后渲染主页否则登录,但每次 redux 是返回未定义为身份验证状态。
这是我的组件
import axios from 'axios';
import jsonwebtoken from 'jsonwebtoken';
import Login from './Containers/Login'
import Home from './Containers/Home'
import {connect } from 'react-redux'
const server = 'http://localhost:5000/api/';
function getCookie(cname) {
let name = cname + "=";
let ca = document.cookie.split(';');
for (let i = 0; i < ca.length; i++) {
let c = ca[i];
while (c.charAt(0) === ' ') {
c = c.substring(1);
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function App({auth, setstate}) {
useEffect(()=>{
const fetchdata = async ()=>{
const token = getCookie('token');
let loggedInUser = {};
if (token !== '') {
try {
loggedInUser = await jsonwebtoken.verify(token, 'shhhhh')._doc;
const res1 = await axios.post(server + 'userlist/getlist', { id: loggedInUser._id });
const res2 = await axios.post(server + 'usertodo/gettodo', { listid: loggedInUser.defaultListid });
if (res1.data.error === null && res2.data.error === null) {
const { lists } = res1.data;
const { todos } = res2.data;
const newState = {
isAuth: true,
loggedInUser,
selectedListid: loggedInUser.defaultListid,
todos,
lists
}
setstate(newState)
}
else{
console.log(res1.data.error, res2.data.error);
setstate({
isAuth:false
})
}
} catch (err) {
console.log(err)
}
}
}
fetchdata();
},[setstate, auth])
return (auth ? <Home/>:<Login/>);
}
const mapStateToProps = state =>{
return {
auth: state.isAuth
}
}
const mapDispatchToProps = dispatch =>{
return {
setstate: async(newState)=> dispatch({type:'SET_STATES', newState})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
================================================ ============================
这是我的初始状态
isAuth: false,
loggedInUser: null,
selectedListid: null,
todos: [],
lists: []
}
和减速器
switch (action.type) {
case 'SET_STATES':
{
const { newState } = action
return {
...state,
...newState
}
}
default:
return state;
【问题讨论】:
标签: javascript reactjs redux react-redux react-state-management