我正在使用react-route,但我在路由方面遇到了一些问题。
整个页面正在重新加载,导致每次都加载我已经获取并存储在reducer中的所有数据。
这是我的路线文件:
var CustomRoute = React.createClass({
render:function(){
return <Router history={browserHistory}>
<Route path="/" component={Layout}>
<IndexRedirect to="/landing" />
<Route path="landing" component={Landing} />
<Route path="login" component={Login} />
<Route path="form" component={Form} />
<Route path="*" component={NoMatch} />
</Route>
</Router>
},
});
在路由之前,我已经通过在 main.jsx 中调用操作来存储数据
/** @jsx React.DOM */
'use strict'
var ReactDOM = require('react-dom')
var React = require('react')
var Index = require('./components/index')
var createStore = require("redux").createStore
var applyMiddleware = require("redux").applyMiddleware
var Provider = require("react-redux").Provider
var thunkMiddleware = require("redux-thunk").default
var reducer = require("./reducers")
var injectTapEventPlugin =require('react-tap-event-plugin');
injectTapEventPlugin()
var createStoreWithMiddleware=applyMiddleware(thunkMiddleware)(createStore);
var store=createStoreWithMiddleware(reducer);
store.dispatch(actions.load_contacts()) //////////// <<<<<< this is what i call to store data already
ReactDOM.render( <Provider store={store}><Index/></Provider> , document.getElementById('content'))
问题是如果登录成功,我必须路由到另一个页面:
this.props.dispatch(actions.login(this.state.login,this.state.password,(err)=>{
this.setState({err:err})
if (!err){
window.location = "/form"
}
}));
window.location 可以解决问题,但它会重新加载所有内容,效率非常低。
在手动 route 我使用<Link\>
该路由无需重新加载,但是对于自动化,我不知道如何做到这一点。
任何建议将不胜感激。
最佳答案
对于最新版本 (v2.0.0-rc5
),推荐的导航方法是直接推送到历史记录单例。
相关代码
import { browserHistory } from './react-router'
browserHistory.push('/some/path')
如果使用较新的react-router API,您需要在组件内部使用this.props
中的history
,因此:
static propTypes = {
history: React.PropTypes.object
}
this.props.history.push('/some/path');
如果使用react-router-redux
,它提供了push
功能,您可以像这样调度:
import { push } from 'react-router-redux';
this.props.dispatch(push('/some/path'));
在v2.4.0及更高版本中,使用更高阶的组件将路由器作为组件的支柱。
import { withRouter } from 'react-router'
class Example extends React.Component {
// use `this.props.router.push('/some/path')` here
};
// Export the decorated class
var DecoratedExample = withRouter(Example);
// PropTypes
Example.propTypes = {
router: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
}).isRequired
};
访问此链接了解更多信息:http://kechengpuzi.com/q/s31079081
关于reactjs - 如何在不重新加载整个页面的情况下进行路由?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39910041/