In my app.js component, I use a function to set the state of current when a click occurs in the saved component. However, I need to reset this state when the route changes and someone is no longer on the saved page.
I was thinking along the lines of resetting the state current whenever there's a route change from the saved component using history. But I'm not sure if that make sense or is doable
Here are parts of app.js
state = {
current: {},
}
handleDetailsClick = (word) => {
console.log(`Fetching details for ${word.word}`);
this.setState({ current: word });
}
setRedirect = redirect =>{
this.setState({redirect})
}
render() {
return (
<>
{ this.state.modal === 'offline' ? <Offline closeModal={() => this.setModal(false)} /> : ''}
<Route
render={ routeProps => <Redirector redirect={this.state.redirect} setRedirect={this.setRedirect} {...routeProps} />}
/>
<header>
<nav className="navbar">
<Link className="navbar-text" to='/'>The Lexicon</Link>
<Link className="navbar-text" to='/savedwords'>Saved</Link>
</nav>
</header>
<main>
<Route
render = { routeProps =>
!routeProps.location.state?.alert ? '' :
<div className="alert alert-primary position-relative float-right m-3">
{ routeProps.location.state.alert }
</div>
}
/>
<Switch>
<Route exact path="/savedwords" render={routeProps =>
<Saved
faves={this.state.faves}
word={this.state.word}
current={this.state.current}
handleSave={this.handleSave}
handleDetailsClick={this.handleDetailsClick}
{...routeProps} />}
/>
<Route path="/404" component={NotFound} />
<Route path="/500" component={InternalServerError} />
<Route component={NotFound} />
</Switch>
</main>
</>
);
}
}
Here is my react router
import React, {Component} from 'react';
class Redirector extends Component {
componentDidUpdate() {
// console.log('Redirector::componentDidUpdate');
const {redirect, location, history, setRedirect} = this.props;
const {path} = redirect;
if (!path) return;
if (path !== location.pathname) {
// console.log('Redirector::performing redirect to', path);
history.push({
pathname: path,
})
}
else {
// console.log('Redirector:: clearing redirect');
setRedirect({});
setTimeout( () => history.replace({state: {}}), 4000);
}
}
render() {
return <></>;
}
}
export default Redirector;
// state: {alert},
// const {path, alert} = redirect;
try to change <Link>
to just <a>
<Link>
will keep the state, but <a>
will request from scratch
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.