我有一些<Link/>
元素和一些通过<Route/>
呈现的相应组件
<Route/>
版的connect
渲染的组件。
单击链接后,地址栏中的URL会更改,但呈现的组件视图不会更改。
但是,正确的视图会在刷新时呈现。
容器组件(带有路由器和链接的组件)的代码
upload.js
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect,
Link
} from "react-router-dom";
import FileUpload1 from "./fileUpload1";
import FileUpload2 from "./fileUpload2";
import FileUpload3 from "./fileUpload3";
export default class Uploads extends Component {
render() {
return (
<div>
<div>
<Link to={`${this.props.match.url}/p`}>Upload 1</Link>
</div>
<div>
<Link to={`${this.props.match.url}/t`}>Upload 2</Link>
</div>
<div>
<Link to={`${this.props.match.url}/e`}>Upload 3</Link>
</div>
<Router>
<Switch>
<Route
path={`${this.props.match.url}/p`}
render={props => (
<FileUploadPassport {...props} tabID="1" />
)}
/>
<Route
path={`${this.props.match.url}/t`}
render={props => <FileUpload2 {...props} tabID="2" />}
/>
<Route
path={`${this.props.match.url}/e`}
render={props => <FileUpload3 {...props} tabID="3" />}
/>
</Switch>
</Router>
</div>
);
}
}
这是 fileUpload1
import React, { Component } from "react";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
class FileUpload1 extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentWillMount() {
console.log("Mounting");
}
componentDidMount() {
console.log("mounted");
}
render() {
return (
<div>
<h1>Hello</h1>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => ({
test: state.initState.testStuff
});
export default withRouter(
connect(mapStateToProps,null)(FileUpload1)
);
我尝试用fileupload1.js
包装withRouter
文件的默认导出,但无济于事。
如何在单击相应的FileUpload1
时获得<Link/>
组件以呈现?
答案 0 :(得分:1)
Link
组件更改了history
上下文中的Router
,因此您需要确保Link
组件在Router
内部呈现。 / p>
只有一个BrowserRouter
component at the top of your app是个好习惯。
export default class Uploads extends Component {
render() {
return (
<Router>
<div>
<div>
<Link to={`${this.props.match.url}/p`}>Upload 1</Link>
</div>
<div>
<Link to={`${this.props.match.url}/t`}>Upload 2</Link>
</div>
<div>
<Link to={`${this.props.match.url}/e`}>Upload 3</Link>
</div>
<Switch>
<Route
path={`${this.props.match.url}/p`}
render={props => <FileUploadPassport {...props} tabID="1" />}
/>
<Route
path={`${this.props.match.url}/t`}
render={props => <FileUpload2 {...props} tabID="2" />}
/>
<Route
path={`${this.props.match.url}/e`}
render={props => <FileUpload3 {...props} tabID="3" />}
/>
</Switch>
</div>
</Router>
);
}
}