如何使用react-router 4.0刷新当前路由?不重新加载整个页面

时间:2017-12-01 22:01:40

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

'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>
        )
    }
}

11 个答案:

答案 0 :(得分:2)

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

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

反应路由器通过使用浏览器历史记录进行导航而无需重新加载整个页面。如果您将路由强加到历史记录中,则React Router将检测到此情况并重新加载路由。替换空路径很重要,这样在将其推入后,后退按钮就不会将您带到空路径。

根据react-router,看来React Router库不支持此功能,并且可能永远不支持,因此您必须以一种怪异的方式强制刷新。

答案 1 :(得分:2)

您可以使用此小技巧。 在历史记录中添加新的路径,例如 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();

通过这种方式,路由将“保持”不变,并将被刷新。

答案 2 :(得分:2)

这就是我实现它的方式:

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

答案 3 :(得分:1)

这是我对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}/>}/>

答案 4 :(得分:1)

调度一个处于初始化状态的动作。

答案 5 :(得分:0)

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

  1. 推动历史的新路径
  2. 重置所有状态
  3. 然后DOM会用你的路线重新渲染。

答案 6 :(得分:0)

这仅对我有用:

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,很好。

答案 7 :(得分:0)

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

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

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

答案 8 :(得分:0)

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

我使用的是 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 :(得分:0)

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

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

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

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

然后,我在路由中设置密钥。

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

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

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

答案 10 :(得分:0)

我在开头使用了重定向,它从 url 的末尾删除了尾部斜杠

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

然后你可以在末尾设置你的路径路径,并且每次都会重新加载。

相关问题