[英]How to reload a URL without refreshing the page in ReactJs?
我正在嘗試重新加載到同一路線而無需刷新頁面。 對於這種特定情況,使用history.pushState()
,但出現錯誤:
類型錯誤:history.pushState 不是函數。
這是我的代碼:
import React from 'react';
import PropTypes from 'prop-types';
import { Container } from 'kawax-js';
import { Switch, Route } from 'react-router-dom';
import File from './FileContainer';
import Folder from './FolderContainer';
import HomeContainer from './HomeContainer';
class RootContainer extends React.Component {
static stateToProps = ({ ownProps, select }) => {
const files = select('files');
const lastFile = _.last(files);
return ({
lastFile: lastFile || {}
})
};
static propTypes = {
history: PropTypes.object.isRequired
};
static defaultProps = {
lastFile: {}
};
render() {
const { lastFile, history } = this.props;
if( lastFile === {} || !lastFile.isUploaded
|| lastFile.isUploaded === null) {
return (
<Switch>
<Route exact path="/" component={HomeContainer} />
<Route exact path="/file/:itemPath/:refHash" component={File} />
<Route exact path="/:folderName" component ={Folder}/>
</Switch>
);
}
return history.pushState(null, "/:folderName")
}
}
export default Container(RootContainer);
有沒有更好的方法來做到這一點,或者我在這里遺漏了什么?
請使用此代碼 Router.browserHistory.push('/'); 修改 history.pushState(null, "/:folderName")
你幾乎沒有辦法做到這一點,目前我最喜歡的方法是在組件 prop 中使用匿名函數:
<Switch>
<Route exact path="/" component={()=><HomeContainer/>} />
<Route exact path="/file/:itemPath/:refHash" component={()=><File/>} />
<Route exact path="/:folderName" component ={()=><Folder/>}/>
</Switch>
或者,如果您想使用當前的 url 參數刷新,則需要額外的路由(重新加載),並使用路由器堆棧進行一些操作:
reload = ()=>{
const current = props.location.pathname;
this.props.history.replace(`/reload`);
setTimeout(() => {
this.props.history.replace(current);
});
}
<Switch>
<Route path="/reload" component={null} key="reload" />
<Route exact path="/" component={HomeContainer} />
<Route exact path="/file/:itemPath/:refHash" component={File} />
<Route exact path="/:folderName" component ={Folder}/>
</Switch>
<div onCLick={this.reload}>Reload</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.