【发布时间】:2020-11-12 08:27:12
【问题描述】:
我刚开始学习 react-redux。我目前正在创建一个登录页面。我想将写在减速器中的布尔状态发送到我的 const,所以当状态为真时,它将执行代码。但是我发送的状态返回未定义。
这是我的减速器
const initState = {
error: "",
loading: false,
loggedIn: false,
};
const authReducer = (state = initState, action) => {
switch (action.type) {
case LOGIN_PENDING:
return {
...state,
loading: true,
loggedIn: false,
};
case LOGIN_SUCESS:
return {
loading: false,
loggedIn: true,
error: "",
};
case LOGIN_ERROR:
return {
loading: false,
loggedIn: false,
error: action.payload,
};
default:
return state;
}
};
export default authReducer;
这是我的行动
export function login(userInfo) {
return (dispatch) => {
dispatch(loginPending());
axios
.post("http://localhost:8000/api/login", {
userName: userInfo["Club"],
password: userInfo["ClubPassword"],
})
.then((res) => {
alert("Sucess");
if (res.data.Result) {
document.cookie = "token=" + res.data.Token;
history.push("/");
}
dispatch(loginSuccess());
})
.catch((error) => {
dispatch(loginError(error.message));
});
};
}
我想知道如何带上我的登录状态并在这条私有路由中使用它
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) =>
loggedIn ? <Component {...props} />
: <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
}
/>
)
编辑:我的 index.js 文件是否有任何错误
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import { Provider } from "react-redux"; // react-redux glues redux to react
import rootReducer from "./Store/Reducers/rootReducer";
import thunk from "redux-thunk";
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);
ReactDOM.render(
<Provider store={store}>
{/* providing store to the app */}
<App />
</Provider>,
document.getElementById("root")
);
【问题讨论】:
-
您应该使用react-redux.js.org/api/connect 或使用useSelector 挂钩将您的组件连接到redux。
标签: reactjs redux react-redux react-router-dom