我正在建立一个多语言网站,需要在URL查询参数中显示当前选择的语言(不仅是语言,为了KISS,我将只考虑这种语言。)
我正在使用react-intl进行网站翻译,并将当前选择的语言存储在redux中。
这是我当前的路由器(HashRouter
)的外观:
return (
<div className="App">
<Provider store={store}>
<Router hashType="noslash">
<Content />
</Router>
</Provider>
</div>
);
}
let Content = connect(state => ({ language: state.common.language }))(props => {
const lang = props.language;
return (
<IntlProvider locale={lang} messages={messages[lang]}>
<Switch>
<Route path='/station_forecasts'>
<StationForecastsPage />
</Route>
<Route path="/">
<Redirect
to={{
pathname: "/station_forecasts",
search: "?sid=76"
}}
/>
</Route>
</Switch>
</IntlProvider>
);
});
我目前的方法是将以下行添加到StationForecastsPage
组件中:
useEffect(() => {
history.push({
pathname: `${window.location.href}`,
search: `?lang=${lang}`
});
});
其中lang
是从redux商店获取的语言代码。但是,它会导致无限循环,并且React会抛出最大深度超出错误。
我也可以使用window.location.href
技巧,但这会导致页面刷新,这显然对我不起作用。
我的问题是实现上述查询参数更新的最佳方法是什么?
答案 0 :(得分:0)
您缺少useEffect
的依赖项,如果您将history
添加为useEffect
的依赖项,则应该起作用:
useEffect(() => {
history.push({
pathname: `${window.location.href}`,
search: `?lang=${lang}`
})
}, [history]);
现在,它将仅在history
更改时运行。