gpt4 book ai didi

javascript - 登录时响应刷新组件

转载 作者:行者123 更新时间:2023-12-02 23:38:31 25 4
gpt4 key购买 nike

我有 2 个组件,导航栏,其中包含登录模式和页面的“主体”。我想检测用户何时登录并据此重新渲染页面。当我使用第一个组件的模式登录时,如何更新第二个组件中的登录属性?

代码的简化版本以保持简短:

//NavBar.js

export default class NavBar extends Component {
constructor(props) {
super(props)
this.initialState = {
username: "",
password: "",
loginModal: false
}
this.handleLogin = this.handleLogin.bind(this)
}
handleLogin(e) {
e.preventDefault()
loginAPI.then(result)
}

render() {
return( <nav> nav bar with links and login button </nav>)
}

//一些随机页面

export default class Checkout extends Component {
constructor(props) {
super(props);
this.state = {
order_type: 'none',
loggedIn: false
}
this.Auth = new AuthService()
}
componentDidMount() {
if (this.Auth.loggedIn()) {
const { username, email } = this.Auth.getProfile()
this.setState({ loggedIn: true, email: email })
}
try {
const { order_type } = this.props.location.state[0]
if (order_type) {
this.setState({ order_type: order_type })
}
} catch (error) {
console.log('No package selected')
}
}

componentDidUpdate(prevProps, prevState) {
console.log("this.props, prevState)
if (this.props.loggedIn !== prevProps.loggedIn) {
console.log('foo bar')
}
}

render() {
return (
<section id='checkout'>

User is {this.state.loggedIn ? 'Looged in' : 'logged out'}

</section>
)
}
}

//App.js

function App() {
return (
<div>
<NavBar />
<Routes /> // This contains routes.js
<Footer />
</div>
);
}

//routes.js

const Routes = () => (
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/register" component={Register} />
<Route exact path="/registersuccess" component={RegisterSuccess} />
<Route exact path="/faq" component={FAQ} />
<Route exact path="/checkout" component={Checkout} />
<Route exact path="/contact" component={Contact} />
{/* <PrivateRoute exact path="/dashboard" component={Dashboard} /> */}
<Route path="/(notfound|[\s\S]*)/" component={NotFound} />
</Switch>
)

最佳答案

我建议使用 React context API 来存储有关登录用户的信息。

参见:https://reactjs.org/docs/context.html

示例

auth-context.js

import React from 'react'

const AuthContext = React.createContext(null);

export default AuthContext

index.js

import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import App from './App'
import AuthContext from './auth-context.js'

const AppWrapper = () => {
const [loggedIn, setLoggedIn] = useState(false)

return (
<AuthContext.Provider value={{ loggedIn, setLoggedIn }}>
<App />
</AuthContext.Provider>
)
}

ReactDOM.render(
<AppWrapper/>,
document.querySelector('#app')
)

然后,您可以在任何组件内导入 AuthContext 并使用 Consumer 组件检查用户是否已登录,以便设置登录状态。

NavBar.js

import React from 'react'
import AuthContext from './auth-context.js'

const NavBar = () => (
<AuthContext.Consumer>
{({ loggedIn, setLoggedIn }) => (
<>
<h1>{loggedIn ? 'Welcome' : 'Log in'}</h1>

{!loggedIn && (
<button onClick={() => setLoggedIn(true)}>Login</button>
)}
</>
)}
</AuthContext.Consumer>
)

export default NavBar

HOC版本

with-auth-props.js

import React from 'react'
import AuthContext from './auth-context'

const withAuthProps = (Component) => {
return (props) => (
<AuthContext.Consumer>
{({ loggedIn, setLoggedIn }) => (
<Component
loggedIn={loggedIn}
setLoggedIn={setLoggedIn}
{...props}
/>
)}
</AuthContext.Consumer>
)
}

export default withAuthProps

测试组件.js

import React from 'react'
import withAuthProps from './with-auth-props'

const TestComponent = ({ loggedIn, setLoggedIn }) => (
<div>
<h1>{loggedIn ? 'Welcome' : 'Log in'}</h1>

{!loggedIn && (
<button onClick={() => setLoggedIn(true)}>Login</button>
)}
</div>
)

export default withAuthProps(TestComponent)

或者,如果您使用 react-redux 设置了 redux,那么它将在幕后使用上下文 API。因此,您可以使用 connect HOC 将登录状态映射到任何组件 props。

关于javascript - 登录时响应刷新组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56192101/

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