简体   繁体   English

刷新浏览器时如何将应用程序重定向到主页?

[英]How to redirect the application to home page when refreshing the browser?

I have a ReactJS application with two pages:我有一个包含两页的 ReactJS 应用程序:

1 - Home Page, where the code requests characters data from Star Wars API ( https://swapi.co/ ); 1 - 主页,代码从 Star Wars API ( https://swapi.co/ ) 请求字符数据;

2 - Characters Page, where the characters data is showned, based on the data extracted from the API in the home page. 2 - 字符页面,其中显示字符数据,基于从主页中的 API 提取的数据。

If I refresh the page when I'm in home page, that's ok.如果我在主页时刷新页面,那没关系。 The data will be requested again.将再次请求数据。 But if I'm in the characters page, it crashes because the characters page doesn't request any data.但是如果我在字符页面,它会崩溃,因为字符页面不请求任何数据。 It works with data already collected in home page.它适用于已在主页中收集的数据。

How can I redirect the user to home page if he or she reloads it in the characters page?如果用户在字符页面中重新加载它,我如何将用户重定向到主页?

I'm using react-router-dom and the home page url is set as "/" and the characters page is "/characters".我正在使用 react-router-dom,主页 url 设置为“/”,字符页面为“/characters”。

I'm also using Redux to store the data.我也在使用 Redux 来存储数据。

Thanks.谢谢。

EDIT: I added the source code for a React/Redux application example that uses axios and redux-thunk to get data from the API.编辑:我添加了 React/Redux 应用程序示例的源代码,该示例使用axiosredux-thunk从 API 获取数据。


Are you using connect() from react-redux on your Characters Page component?您是否在 Characters Page 组件上使用react-redux connect()

If not, you can do the following:如果没有,您可以执行以下操作:

import { connect } from 'react-redux'

const CharactersPage = props => {
    // You can retrieve your data from props.characterData

    return ...
}

const mapStateToProps = state => {
    return { characterData: state.characterData }
}

export default connect(mapStateToProps)(CharactersPage)

This should solve the issue of your Characters Page crashing on reload because it doesn't have the data.这应该可以解决您的角色页面在重新加载时崩溃的问题,因为它没有数据。

And if you really need to redirect users to the / page, you can utilize the history object.如果你真的需要将用户重定向到/页面,你可以使用history对象。 It automatically gets passed down when you set up your routes using <Route> from react-router-dom , given that you set up your route as such:当您使用react-router-dom <Route>设置您的路线时,它会自动传递下去,假设您设置了您的路线:

<Route path='/characters' component={CharactersPage} />

If you use render={} instead, you can get the history object by doing:如果您改用render={} ,则可以通过执行以下操作来获取history对象:

<Route path='/characters' render={routeProps => <CharactersPage {...routeProps} />} />

I hope this helps!我希望这有帮助!

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

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