reactjs - react-router4 更改了 URL,但路由与要渲染的新 URL 不匹配
问题描述
解决方案
由于您this.props.history.push
在 Routes 组件中使用,因此您需要将此组件包装为withRouter
class Routes extends Component {
constructor(props) {
super(props);
this.URLChange = this.URLChange.bind(this);
this.getOwnState = this.getOwnState.bind(this);
this.state = this.getOwnState();
}
getOwnState() {
return {
currentURL: store.getState()["currentURL"]
};
}
URLChange() {
console.debug(this.getOwnState()["currentURL"]);
this.props.history.push(this.getOwnState()["currentURL"]);
//setState是异步的
let currentURL = this.getOwnState()["currentURL"];
this.setState(Object.assign({
currentURL
}, {currentURL}), () => {
//回调方法
console.debug("1:" + this.state.currentURL)
})
}
componentDidMount() {
store.subscribe(this.URLChange);
}
render() {
alert("render:" + JSON.stringify(this.props.history.location.pathname));
return (<BrowserRouter >
<Switch>
<Route path="/LoginPage" component={LoginPage}/>
<Route path="/SuccessPage" component={SuccessPage}/>
<Route path="/errorPage" component={errorPage}/>
<Route path="/*" component={errorPage}/>
</Switch>
</BrowserRouter>);
}
}
export default withRouter(Routes);
推荐阅读
- python - 计算聚类精度
- macos - Mac OSX 上的 Microsoft VS Code:没有出现在 OSX(屏幕顶部)菜单栏中
- c - C99 是否总是要求 `int64_t` 类型可用?
- php - $record 没有传递值
- excel - 获取列中每个唯一值的范围的宏
- python - ANSI 代码在字符串的 ndarray 中不起作用
- javascript - 重置内部状态时使用什么代替 componentWillReceiveProps
- node.js - 变量未显示在 ejs 模板中
- azure-ad-b2c - 如何使用 B2C 自定义策略对手机进行身份验证
- html - 如何通过垂直中心居中块?