3
自從我開始使用react/redux並且我在使用Redirect
組件時,我正在第一次使用react-router-dom應用程序。在react-router-dom中重定向?
我想發射Redirect
當驗證成功但它不會重定向到我想要驗證後的頁面。
index.js
import { BrowserRouter as Router, Route } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import App from './components/app';
import Page1 from './containers/page1';
import Signin from './containers/auth/signin';
import Reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxThunk)(createStore);
const store = createStoreWithMiddleware(Reducers);
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
<Route path="/" component={App}/>
<Route path="/" component={Signin}/>
<Route path="/signin" component={Signin}/>
<Route path="/page1" component={Page1}/>
</div>
</Router>
</Provider>
, document.querySelector('.container'));
signin.js
import { BrowserRouter as Route, Redirect } from 'react-router-dom';
import { userSignin } from '../../actions/index';
class Signin extends Component {
constructor(props) {
super(props);
this.state = { username: '', password: '' };
this.handleSubmit = this.handleSubmit.bind(this);
this.handleUsernameChange = this.handleUsernameChange.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
componentWillUpdate(nextProps) {
if (this.props.authenticated !== nextProps.authenticated) {
if (nextProps.authenticated) {
console.log('true?', nextProps.authenticated)
return (
<Redirect to="/page1" />
);
}
}
}
handleSubmit(e) {
e.preventDefault();
this.props.userSignin({ username: this.state.username, password: this.state.password });
this.setState({ username: '', password: '' });
}
.....
render() {
return (
<form onSubmit={this.handleSubmit}>
<input
placeholder="username"
value={this.state.username}
onChange={this.handleUsernameChange}
/>
<input
placeholder="password"
type="password"
value={this.state.password}
onChange={this.handlePasswordChange}
/>
<span>
<button type="submit">SIGNIN</button>
</span>
{this.renderError()}
</form>
);
}
}
function mapStateToProps(state) {
return {
authenticated: state.auth.authenticated,
errMsg: state.auth.err
};
}
function mapDispatchToProps(dispatch) {
return {
userSignin: ({ username, password }) => dispatch(userSignin({ username, password }))
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Signin);
在這段代碼,這樣做登錄true?
但它不會重定向到/page1
。
正如我所提到的,這是我第一次使用react-router-dom
庫,對於我在代碼中存在的任何愚蠢錯誤,我表示歉意。
謝謝你,請洞察我!
你說它不會重定向到'/ page1'路線。它到底在哪裏? –
它保留在'/'路線中。 – ckim16
Ook ...嘗試使用'精確路徑'作爲你的'/'路由,因爲這將匹配所有其他路由。讓我知道這是否可行,以便我可以將其添加到答案中。 ' ' –