gpt4 book ai didi

javascript - 无法在第一页加载时获取参数

转载 作者:行者123 更新时间:2023-11-28 19:13:40 25 4
gpt4 key购买 nike

我正在尝试为我的 React 应用程序中的某些页面应用多个背景主题。为此,我的方法是从 url 中读取页面名称,并根据页面名称应用多个主题。

我已经创建了一个布局来呈现我的组件,然后我试图从那里从 url 中读取页面名称。

我的方法

const HomeLayout = ({ component: Component, ...rest }) => {

const activePage = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');
const gradientPages_type1 = ['consumer_add', 'myprofile', 'nfc_add','evc_detail'];
const gradientPages_type2 = [''];
const gradientPages_type3 = ['dashboard']


return (
<PrivateRoute {...rest} render={matchProps => (
<div id="">
<div className="DefaultLayout mx-auto" id={gradientPages_type1.includes(activePage) ?
'bg_gradient' : gradientPages_type2.includes(activePage) ? 'bg_gradient2' : gradientPages_type3.includes(activePage) ?'bg_gradient3':'bg_normal'}>
<div className="Header"><Header /></div>
<div><Component {...matchProps} /></div>
</div>
</div>
)} />
)
};

export default HomeLayout;

但我面临的问题是我只能在第二次刷新时获得 activePage。如果我正常浏览我的应用程序,我将无法获取 activePage 但再次刷新后我可以获得页面名称。我怎样才能在第一次呈现时获得 activePage。我试着让我的 HomeLayout 成为一个类,并试图在 componentDidMount 上获取事件页面,但仍然无法从我的 url 获取页面名称。有解决办法吗?

我的 App.js

function App() {

const authenticateUser = {
isAuthenticated: false,
authenticate() {
if (token) {
this.isAuthenticated = true;
} else {
this.isAuthenticated = false;
}
}
};

return (

<div>
{authenticateUser.authenticate()}
<Switch>
<AuthContext.Provider value={authenticateUser.isAuthenticated}>
<LoginLayout path="/" component={Login} exact />
<LoginLayout path="/register" component={Register} />
<HomeLayout path="/dashboard" component={Dashboard} />
<HomeLayout path="/evc" component={EvcStations} />
<HomeLayout path="/nfc" component={NfcContainer} />
<Route component={FourNoteFour} />
</AuthContext.Provider>
</Switch>
</div>

);
}

索引.js

ReactDOM.render(<Provider store={store}><Router history={history}><App /></Router></Provider>, document.getElementById('root'));

最佳答案

问题是我正在使用我的 <AuthContext.Provider value={authenticateUser.isAuthenticated}>在我的里面 Switch .我所要做的就是服用 AuthContext在 Switch 之外,它工作正常。

关于javascript - 无法在第一页加载时获取参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58837323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com