当我想从页面上的静态链接进行路由时,来自index.js的以下代码片段对我来说工作正常-
import React from 'react';
import ReactDOM from 'react-dom';
import LoginForm from './components/LoginForm/LoginForm';
import { Provider } from 'react-redux';
import store from './redux/store';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Home from './components/Home.js'
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
<h2>My Page</h2>
<ul>
<li><Link to={'/'}>LoginForm</Link></li>
<li><Link to={'/home'}>Home</Link></li>
</ul>
<hr />
<Switch>
<Route exact path='/' component={LoginForm} />
<Route exact path='/home' component={Home} />
</Switch>
</div>
</Router>
</Provider>,
document.getElementById('root')
是否可以转到代码内的另一页,例如?
updateStore(loggedIn){
const action = {type:loggedIn};
store.dispatch(action);
if(loggedIn==='LOGGED_IN'){
console.log("I am In");
//route me into another page ??
}else{
console.log("I am out");
}
}
答案 0 :(得分:2)
得到我的答案here
创建了自己的route.js
import React from 'react';
import { Route, Switch } from 'react-router';
import LoginForm from './components/LoginForm/LoginForm';
import Home from './components/Home';
class RouteList extends React.Component {
render() {
return (
<Switch>
<Route exact path="/" component={LoginForm} />
<Route path='/home' exact={true} component={Home}></Route>
</Switch>
);
}
}
export default RouteList;
然后在index.js中-
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './redux/store';
import RouteList from './route';
import { Router } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'
export const history = createBrowserHistory()
ReactDOM.render(
<Provider store={store}>
<Router history={history}>
<RouteList></RouteList>
</Router>
</Provider>,
document.getElementById('root')
);
最后在我的action.js中-
import { history } from '../index';
callLoginApi(email, password, error => {
dispatch(setLoginPending(false));
if (!error) {
dispatch(setLoginSuccess(true));
history.push('/home');
} else {
dispatch(setLoginError(error));
}
});
答案 1 :(得分:0)
您可以为此使用react-router
npm我反应路由器--save
在您的组件中执行以下操作
import {browserHistory} from 'react-router';
callback = () => {
browserHistory.push('/home');
}