我正在使用React 4,并具有发布这样的路由的顶级组件
<Route path={testingUrl}>
<TestingPage />
</Route>
TestingPage组件是
import React from "react";
import { BrowserRouter, Route, withRouter } from "react-router-dom";
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
const DropDown = () => {
const onChange = (e) => {
history.push(`/aaa/testing/${e.target.value}`);
}
return (
<select onChange={onChange}>
<option value="first-route">First</option>
<option value="second-route">Second</option>
</select>
);
}
const Menu = withRouter(DropDown);
export default function TestingPage() {
return (
<BrowserRouter>
<div>
<Route path="/aaa/testing/first-route" render={() => <h1>First Selected</h1>} />
<Route path="/aaa/testing/second-route" render={() => <h1>Second Selected</h1>} />
<Menu />
</div>
</BrowserRouter>
);
}
我在下拉列表中选择了第二项,URL已正确更新为“ / aaa / testing / second-route”,但未显示“第二选择项”。我不明白为什么。
请注意,我不想做任何会丢失React上下文内容的事情。
答案 0 :(得分:0)
我认为问题在于thr DropDown组件正在使用与浏览器路由正在监视的更改不同的“历史记录”。
如果您希望下拉列表使用与BrowserRouter相同的历史记录,则需要它使用withRouter传递的prop而不是使用createBrowserHistory创建第二个。
import React from "react";
import { withRouter } from "react-router-dom";
const DropDown = props => {
const {history} = props;
const onChange = (e) => {
history.push(`/aaa/testing/${e.target.value}`);
}
return (
<select onChange={onChange}>
<option value="first-route">First</option>
<option value="second-route">Second</option>
</select>
);
}
const Menu = withRouter(DropDown);
如果您绝对需要使用自定义历史记录对象(例如,如果您传递基本URL),则需要在创建它时将其传递给BrowserRouter,而不是下拉列表。
答案 1 :(得分:0)
谢谢大卫,我想念过去的历史。更改为 const DropDown =({历史})=> { 工作:-)