请帮助我,如何从子组件reactjs重新渲染父组件默认路由?看到以下gif
Dashboard.jsx
import React, { Component } from "react";
import { BrowserRouter, Redirect, Switch, Route, Link } from "react-router-dom";
import { withRouter } from "react-router";
import Master from "./Master";
import Pos from "./Pos";
import IndexDashboard from "./IndexDashboard";
import NotFound from "./404";
class Dashboard extends Component {
constructor(props) {
super(props);
this.state = {
islogout: false
};
}
signOut = () => {
localStorage.removeItem("token");
this.setState({
islogout: true
});
};
render() {
if (this.state.islogout) {
return <Redirect to="/login" />;
}
const { match } = this.props;
return (
<BrowserRouter>
<div className="container-fluid">
<ul>
<li>
<Link to={`${match.path}`}>Dashboard</Link>
</li>
<li>
<Link to={`${match.path}/master`}>Master</Link>
</li>
<li>
<Link to={`${match.path}/pos`}>Pos</Link>
</li>
<li onClick={this.signOut}>signOut</li>
</ul>
<main role="main">
<div className="main">
<Switch>
<Route path={`${match.path}/master`}>
<Master />
</Route>
<Route path={`${match.path}/pos`}>
<Pos />
</Route>
<Route exact path={`${match.path}`}>
<IndexDashboard />
</Route>
<Route path="*">
<NotFound />
</Route>
</Switch>
</div>
</main>
</div>
</BrowserRouter>
);
}
}
export default withRouter(Dashboard);
Master.jsx
import React, { Component, Fragment } from "react";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import NewItem from "./NewItem";
import ListItem from "./ListItem";
import NotFound from "./404";
import { withRouter } from "react-router";
class Master extends Component {
constructor(props) {
super(props);
console.log(this.props);
}
render() {
const { match } = this.props;
console.log("match", match);
return (
<Fragment>
<h2>Master Item</h2>
<BrowserRouter>
<div className="container">
<Switch>
<Route path={`${match.path}/new`} component={NewItem} />
<Route exact path={`${match.path}`} component={ListItem} />
<Route path="*" component={NotFound} />
</Switch>
</div>
</BrowserRouter>
</Fragment>
);
}
}
export default withRouter(Master);
ListItem.jsx
import React, { Component, Fragment } from "react";
import { Link } from "react-router-dom";
class ListItem extends Component {
render() {
const { match } = this.props;
return (
<Fragment>
<Link to={`${match.path}/new`}>New Item</Link>
<h2>List Item</h2>
</Fragment>
);
}
}
export default ListItem;
问题是当我从新项目页面导航回主路径时,默认路径(列表项)未重新呈现。
这是我的密码和框https://codesandbox.io/s/react-bootstrap-3cpsd
谢谢
答案 0 :(得分:0)
在子组件中,您可以仅呈现onclick事件
而不是使用React-Routerimport React, { Component, Fragment } from "react";
import { Link } from "react-router-dom";
class ListItem extends Component {
constructor(props){
super(props);
this.state.isClicked = false;
}
handleClick = () => {
this.stateState({isClicked: true});
};
render() {
const { match } = this.props;
return this.state.isClicked ? (
<Parent />
): (
<Fragment>
<Link onClick={this.handleClick}>New Item</Link>
<h2>List Item</h2>
</Fragment>
);
}
}
export default ListItem;