I'm defining routes for a React project in a way that the URL looks like http://something.com/en-us/home or http://something.com/fr-ca/home by doing:
<Route path="/:language/home" render={() => <Home/>}/>
In planning for a case where the path variable ":language" is a not a real language (ie redirect http://something.com/xyz/home to http://something.com/en-us/home ), I originally invoked the method setDefaultLanguage
within componentDidMount
, which was intended to refresh the page with the browser's language code. Instead, this method refreshes the page each time that it mounts.
checkLangInMasterList(code) {
let index = Object.keys(langMasterList).indexOf(code);
// langMasterList is a JSON file with codes for 15
// languages that the website will be offered in
return index === -1 ? false : true;
}
setDefaultLanguage() {
let browserLanguage = navigator.language || navigator.browserLanguage;
let pathnames = window.location.pathname.split("/");
// i.e. pathnames would look like
// ["", "xyz", "home"]
if (checkLangInMasterList(pathnames[1]) !== -1) {
return;
} else if (checkLangInMasterList(browserLanguage) === -1) {
window.location = `/en-us/${pathnames[2]}`;
} else if (
checkLangInMasterList(pathnames[1]) === -1 &&
checkLangInMasterList(browserLanguage) !== -1
) {
window.location = `/${browserLanguage}/${pathnames[2]}`;
}
}
If the browser's language code doesn't exist (either at all or within the allowed languages list), how do I properly handle a redirect to either the user's browser language (if supported in our list) or to en-us
?
Your checkLangInMasterList
return a boolean not -1. Your code should look like this:
if (!checkLangInMasterList(pathnames[1])) {
// do stuff here
}
also, if the path variable equals the browser language you should stop the redirect.
So according to the logic you want here is how it will look like:
if (checkLangInMasterList(pathnames[1]) {
return
}
if (checkLangInMasterList(browserLanguage) {
window.location = `/${browserLanguage}/${pathnames[2]}`
} else {
window.location = `/${en-us}/${pathnames[2]}`
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.