繁体   English   中英

重定向更改时重置状态

[英]Reset State On Redirect Change

在我的 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;

尝试将<Link>更改为<a>

<Link>会保持状态,但<a>会从头开始请求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM