React Router 4:使用具有历史记录的路由参数更改路由



我是React框架的新手,现在正在开发一个简单的Redux网络应用程序。

如果用户在主页上(http://localhost/xyz/home)如果我使用history.push('/xyz/profile'(推送下一个状态,我会在URL中获得两次用户id(xyz((http://localhost/xyz/home/xyz/profile)

如何更改状态?

谢谢,MSK

实际

import shareService from "../services/share.service";
import history from "../utils/history";
import _ from 'lodash';
export const shareUserInfo = (info) => dispatch => {
shareService.shareUserInfo(info)
.then(res => {
history.push('/xyz/profile');
},
error => {
console.log(error);
});
}

In history.js
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
export default history;

如果您有权访问React Router的match属性,请从match.url获取url。

这不是一个干净的代码(因为它只是一个演示(&遗漏了一些代码
工作代码可在CodeSandBox上获得。

const App = ({ match, history }) => (
<div className="App">
<h1>Home</h1>
<h2>Some 🏡 data</h2>
<button onClick={e => toProfile(e, match.url, history)}>Profile</button>
</div>
);
const toProfile = (e, url, history) => {
e.preventDefault();
console.log(`url=${url}`);
history.push("/xyz/profile");
};
const toHome = (e, url, history) => {
e.preventDefault();
console.log(`url=${url}`);
history.push("/xyz/home");
};
const rootElement = document.getElementById("root");
ReactDOM.render(
<BrowserRouter>
<Switch>
<Route exact path="/" component={App} />
<Route path="/xyz/home" component={App} />
<Route path="/xyz/profile" component={Profile} />
</Switch>
</BrowserRouter>,
rootElement
);