クリックすると次の関数を呼び出すログインフォームがあります。
要約すると、有効な場合は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を削除した場合)、目的のディレクトリに強制的に移動し、再度ログインを試みることを意味します。今回はリダイレクトが機能します。
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をインポートします。import {Redirect} from'react-router ';
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":{}}}
いつどこでisAuthenticatedを設定しますか?– lehm.ro 7分前
のcomponentDidMount()中の私のapp.jsの@ lehm.ro、デフォルトのisAuthenticatedはfalse – mouchin777 6分前そしてリダイレクトしたら、this.setStateを使用してtrueにする必要があります。プライベートルートは表示されません。ただし、そのためには、真の状態をapp.jsに渡してから、isAuthenticated trueのsetStateに関数をトリガーしてから、そのルートにリダイレクトする必要があります。
小道具に渡されることなくapp.jsで動作するように履歴を設定します:Uncaught TypeError:undefinedのプロパティ 'push'を読み取れません(React-Router-Dom)
コンポーネントで使用するに
history
は、でApp
使用しwithRouter
ます。withRouter
コンポーネントが、を受信していない場合にのみ使用する必要があります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);
withRouterの[ドキュメント] [1]
[1]:https://reacttraining.com/react-router/web/api/withRouter
App.jsの変更
<Route exact path="/login" render={(props) => <LoginPage login={this.login} {...props} />} />
と追加
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)
})
}
およびLoginPageで
handleSubmit(event) {
const { email, password } = this.state;
this.props.login(email, password)
event.preventDefault();
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加