【问题标题】:How to use react-router 4.0 to refresh current route? not reload the whole page如何使用 react-router 4.0 刷新当前路由?不重新加载整个页面
【发布时间】:2018-05-16 01:44:32
【问题描述】:

'react-router-dom'有刷新功能here,但是我不知道怎么调用这个方法,他们的well formatted document也懒得解释了。

window.location.reload() 对我不起作用,因为它也会清除应用商店。我更改了一些数据,然后需要使用更新的数据重新加载路线。

我也读过这个: https://github.com/ReactTraining/react-router/issues/1982 https://github.com/ReactTraining/react-router/issues/2243

这个帖子正是在讨论我的问题: https://github.com/ReactTraining/react-router/issues/4056

仍然不知道该怎么做。这个基本功能应该不需要太多的努力,但是在花费了巨大的努力之后,我无法重新加载当前的路线。

这是我的代码:

@inject('store') @observer
export default class PasswordInput extends Component {
    constructor (props) {
        super(props)
        this.setPwd = this.setPwd.bind(this)
        this.submit = this.submit.bind(this)
    }

    componentWillMount() {
        this.case = this.props.store.case

        this.setState({refresh: false})
    }
    setPwd(e) {
        // console.log(e)
        this.case.pwd = e.target.value

    }
    submit() {
        console.log(this.props.caseId)
        this.setState({refresh: true})

    }

    render() {
        return (
            <Container>
                <div>{this.state.refresh}</div>
                { (this.state.refresh) && <Redirect refresh={true} to={'/cases/' + this.props.caseId}></Redirect>}
                <br />
                <Grid columns="three">
                    <Grid.Row>
                        <Grid.Column key={2}>
                            <Form>
                                <label>Enter Password</label>
                                <input placeholder="empty"  type="text" onChange={this.setPwd} value={this.case.pwd}></input>                               

                                <Button name="Save" color="green" size="mini" 
                                style={{marginTop:'1em'}}
                                onClick={this.submit}>
                                    Submit
                                </Button>                               
                            </Form>
                        </Grid.Column>
                    </Grid.Row>
                </Grid>
            </Container>
        )
    }
}

【问题讨论】:

标签: reactjs react-router react-router-v4


【解决方案1】:

我有同样的问题,我不知道刷新是怎么做的。我的解决方案是执行以下两个步骤。

  1. 推动历史新路径
  2. 重置所有状态

然后 DOM 将使用您的路线重新渲染。

【讨论】:

    【解决方案2】:

    我通过将新路线推送到历史记录中解决了这个问题,然后用当前路线(或您要刷新的路线)替换该路线。这将触发 react-router 在不刷新整个页面的情况下“重新加载”路由。

    if (routesEqual && forceRefresh) {
        router.push({ pathname: "/empty" });
        router.replace({ pathname: "/route-to-refresh" });
    }
    

    React 路由器的工作原理是使用您的浏览器历史记录进行导航,而无需重新加载整个页面。如果你强制一个路由进入历史,react 路由器会检测到这个并重新加载路由。替换空路线很重要,这样您的后退按钮不会在您按下后将您带到空路线。

    根据react-router 看来,react 路由器库不支持此功能,而且可能永远不会支持,因此您必须以一种骇人听闻的方式强制刷新。

    【讨论】:

      【解决方案3】:

      只有这对我有用:

      reloadOrNavigate = () => {
        const { history, location } = this.props;
        if (location.pathname === '/dashboard') {
          history.replace(`/reload`);
          setTimeout(() => {
            history.replace(`/dashboard`);
          });
        } else {
          history.push('/dashboard');
        }
      };
      

      答案与上一个类似,但我需要添加setTimeout 函数才能使其工作。就我而言,如果我在 /dashboard 页面上,我必须通过单击徽标来刷新当前 URL。首先,它转到额外的路线/reload(名称由您决定),然后立即返回。页面变为白色不到一秒钟,并显示重新加载的数据。浏览器没有重新加载,它仍然是 SPA,这很好。

      【讨论】:

      • 虽然这可能会回答这个问题,但您应该 edit 您的回答包括您的代码如何回答这个问题,以便为未来的读者提供上下文。代码块本身对于以后可能遇到相同问题的人不会立即有用。
      【解决方案4】:

      这是我使用 react-router-dom 的“重定向”的解决方案:

      <Route key={props.notifications.key} path={props.notifications.path} exact render={() => <Redirect to={props.notifications.path + "/update"}/>}/>
      <Route key={props.notifications.key + "/update"} path={props.notifications.path + "/update"} exact render={() => <props.notifications.component apis={props.notifications.apis}/>}/>
      

      【讨论】:

        【解决方案5】:

        你可以使用这个小技巧。 像 history.push('/temp') 这样在历史中推送一条新路径并立即调用 history.goBack()

        这里是例子:

        创建历史并将其传递给路由器:

        import { createBrowserHistory } from "history";
        
        export const appHistory = createBrowserHistory();
        
        <Router history={appHistory}>
          <Route exact path="/" component={Home} />
          <Route path="/about" component={About} />
        </Router>
        

        然后在您的应用程序的某个地方,更改历史记录:

        appHistory.push('/temp');
        appHistory.goBack();
        

        这样,路线将“保持”不变,并会被刷新。

        【讨论】:

          【解决方案6】:

          这就是我实现它的方式:

          if (currentUrl == newUrl) {
              props.history.push("/temp");
              props.history.goBack();
          }
          

          【讨论】:

            【解决方案7】:

            我不知道 react-router 是否已经解决了这个问题,但就我而言。我创建了一条路径名刷新的新路由,在第一次渲染组件时会返回

            <Route
                path="/refresh"
                exact
                component={() => {
                   useEffect(() => history.goBack(), []);
                   return <></>;
                }}
             />
            

            所以当我想刷新路线时。我只是推动刷新路线,然后返回然后呈现新的重新加载结果;

            【讨论】:

              【解决方案8】:

              好吧,我之前尝试过几乎所有的答案,但没有任何效果。这是我可以强制重新加载的唯一方法

              我正在使用 redux,但您也可以使用您喜欢的任何状态管理

              1 - 将布尔值设置为 false

              2 - 向您的链接/按钮添加一个 onClick 函数,将布尔值设置为 true

              3 - 将该布尔变量添加到 useEffect()

              这将触发重新渲染

              useEffect(() => {
                 // Do stuff...
              },[forceReload])
              
              const forceReload = () => {
                 dispatch({ type: RELOAD });
                 // OR useState or whatever you want
                 setForceReload(true);
              }
              
              
              ...
              <Link onClick={forceReload} to="/my-path-that-does-not-reload">
                 Reload Page
              </Link>
              

              这对我来说适用于链接和 HTML 按钮标签

              【讨论】:

                【解决方案9】:

                我在我们的应用中使用 key 和 state 来解决这个问题。

                在我的例子中,我们希望在单击同一个菜单时不完全重新加载而刷新,即使它已经处于活动状态。

                所以,在我们的菜单点击中,我有这个代码。它不必是uuid,它可以是任何东西,只要它每次触发时都会改变。它也不必是带有 reloadKey 属性的对象,这取决于您。可以是简单的字符串,我就是这么写的。

                push({state: {reloadKey: uuid()}}); 
                

                然后,我在 Route 中设置密钥。

                PrivateRoute 是我包装来自 react-router-dom 的 Route 的包装器。

                const {state: { reloadKey } = {}}  =  location;
                <PrivateRoute key={reloadKey} path="/path" component={Component} />
                

                因为key改变了,这会触发组件重新挂载,不会触发整页重新加载。

                【讨论】:

                  【解决方案10】:

                  我在开头使用redirct,它从url末尾删除了斜杠

                   <Redirect key={0} from="/:url*(/+)" to={pathname.slice(0, -1)} />
                  

                  然后您可以在末尾设置带有斜杠的路由路径,并且每次都会重新加载。

                  【讨论】:

                    最近更新 更多