我有一个登录表单,单击该表单将调用以下功能。
摘要,从api获取响应(如果有效),设置cookie,然后使用this.props.history.push()
handleSubmit(event) {
event.preventDefault();
const { email, password } = this.state;
axios({
method: 'post',
url: 'http://localhost:3003/login',
data: qs.stringify({ email, password }),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(res => {
console.log("set cookie")
//the accestoken is set as a cookie in order to check routes
Cookies.set('accesstoken', res.data.accesstoken);
console.log("those are the props")
console.log(this.props);
this.props.history.push('/'); //the bug
}).catch(err => {
console.log(err)
})
}
但是我面临的问题是,当我第一次登录时,重定向将无法工作。它设置所有cookie以及所有cookie,但实际上不会将用户重定向到所需目录。因此,我被迫通过在浏览器搜索栏中输入所需的路线来重定向自己。
这意味着一旦我注销(基本上删除cookie),然后强迫自己进入所需的目录,然后尝试再次登录。这次重定向有效。
它将一直工作到我用ctrl + F5清除所有缓存时,碰巧会导致与第一次登录时相同的问题,因此我不得不再次手动重定向自己。
编辑:这是我的路线的样子
<BrowserRouter>
<Switch>
<Route exact path="/login" render={(props) => <LoginPage {...props}/>} />
<PrivateRoute authed={this.state.isAuthenticated} exact path="/" render={(props) => <RegisterPage />} />
</Switch>
</BrowserRouter>
那是我的私人路线
import { Route } from 'react-router-dom';
从'react'导入React; 从“反应路由器”导入{重定向};
export default ({ component: Component, render: renderFn, authed, ...rest }) =>{
//The privateroute is fed with the auth state of app.js and evaluates the render based on that . If flase always renders "/"
if (Component){
return (
<Route
{...rest}
render={props =>
authed === true ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
)
} else {
return ( //Second case is for iframe based renders
<Route {...rest} render={props => authed === true ? renderFn(props) : <Redirect to={{ pathname: '/login', state: { from: props.location } }} /> } />
);
}
}
EDIT2:
app.js
constructor(props) {
super(props);
console.log("PROPS APPJS")
console.log(props)
//checks if user is autheticated within the system in order to manage routes
this.state = {
authenticationChecked: false,
isAuthenticated: false
}
}
componentDidMount() {
//calls the auth service to decide the auth state value
isAuthenticated().then((result) => {
if (result === true) {
this.setState({ isAuthenticated: true, authenticationChecked: true})
} else {
this.setState({ isAuthenticated: false, authenticationChecked: true})
}
});
}
login = (email, password) => {
var thiscomponent = this;
axios({
method: 'post',
url: 'http://localhost:3003/login',
data: qs.stringify({ email, password }),
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
}
}).then(res => {
console.log("set cookie")
//the accestoken is set as a cookie in order to check routes
Cookies.set('accesstoken', res.data.accesstoken);
console.log("those are the props")
console.log(this.props);
this.setState({ isAuthenticated: true }, () => {
thiscomponent.props.history.push('/'); //the bug
})
}).catch(err => {
console.log(err)
})
}
.
.
.
.
.
.
.
<BrowserRouter>
<Switch>
<PrivateRoute authed={this.state.isAuthenticated} exact path="/" render={(props) => <NewLandingPage login={this.login} {...props} exact />} />
</Switch>
</BrowserRouter>
登录页面
handleSubmit(event) {
const { email, password } = this.state;
this.props.login(email, password)
event.preventDefault();
}
编辑:登录页面道具
{"history":{"length":15,"action":"POP","location":{"pathname":"/login","search":"?email=test4%40test.com&password=test","hash":""}},"location":{"pathname":"/login","search":"?email=test4%40test.com&password=test","hash":""},"match":{"path":"/login","url":"/login","isExact":true,"params":{}}}
答案 0 :(得分:1)
您在哪里以及何时设置isAuthenticated? – lehm.ro 7分钟前
在componentDidMount()期间在我的app.js中使用@ lehm.ro,默认isAuthenticated为false – mouchin777 6分钟前
然后,一旦重定向,就必须使用this.setState使其为true,否则您的私有路由将不会显示。但是为此,您需要将true状态传递给app.js,然后为isAuthenticated true触发一个函数到setState,然后重定向到该路由
设置您的历史记录以在app.js中工作而不会被道具传递: Uncaught TypeError: Cannot read property 'push' of undefined (React-Router-Dom)
为了在
store[i++] = src
组件中使用string HTML entities ( string $string [, int $flags = ENT_COMPAT | ENT_HTML401 [, string $encoding = ini_get("default_charset") [, bool $double_encode = true ]]] )
,请与history
一起使用。您仅在以下情况下需要使用App
: 组件未收到withRouter
,如果您的组件是某个产品的嵌套子产品,则可能会发生这种情况 路由器呈现的组件或您尚未通过路由器 或当组件未链接到路由器时 全部,并与路线分开显示。
withRouter
[文档] [1] onrouter
[1]:https://reacttraining.com/react-router/web/api/withRouter
App.js中的更改
Router props
并添加
import React from 'react';
import { Route , withRouter} from 'react-router-dom';
import Dashboard from './Dashboard';
import Bldgs from './Bldgs';
var selectedTab;
class App extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
selectedTab = 0;
}
handleClick(value) {
selectedTab = value;
// console.log(selectedTab);
this.props.history.push('/Bldgs');
// console.log(this.props);
}
render() {
var _this = this;
return (
<div>
<Route exact path="/" render={(props) => <Dashboard {...props} handleClick={_this.handleClick} />} />
<Route path="/Bldgs" component={Bldgs} curTab={selectedTab} />
</div>
);
}
}
export default withRouter(App);
和在LoginPage中
<Route exact path="/login" render={(props) => <LoginPage login={this.login} {...props} />} />