【发布时间】:2021-03-04 23:46:09
【问题描述】:
在我的 app.js 组件中,我使用一个函数来设置在保存的组件中发生单击时的当前状态。但是,当路线更改并且有人不再在保存的页面上时,我需要重置此状态。
每当使用历史记录保存的组件发生路由更改时,我都在考虑重置当前状态。但我不确定这是否有意义或可行
这里是 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>
</>
);
}
}
这是我的反应路由器
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;
【问题讨论】:
标签: reactjs redirect react-router initialization state