如何使用 Context API 访问状态
2019-04-22
1890
我在 React 应用程序中使用 context API 进行状态管理,并且正在寻找一种从我的 Provider 类中以无状态函数访问状态的方法。
我熟悉在 render() 内部将 Consumer 标签包装在 JSX 周围,但在这种情况下,我不会返回任何 JSX
app.js
export default class App extends Component {
render() {
return (
<BrowserRouter>
<Provider>
<Header />
<Switch>
<PrivateRoute path='/test' component={test} />
</Switch>
</Provider>
</BrowserRouter>
);
};
};
/context/index.js (Provider 类)
import React, { Component } from 'react';
import axios from 'axios';
import {withRouter} from 'react-router';
const AuthContext = React.createContext();
class Provider extends Component {
state ={
firstName: '',
lastName:'',
emailAddress: '',
password: '',
signedIn: false,
};
render(){
return (
<AuthContext.Provider value = {{
user: {...this.state},
}}>
{this.props.children}
</AuthContext.Provider>
);
};
};
export default withRouter(Provider);
export const Consumer = AuthContext.Consumer;
PrivateRoute.js
import React from 'react';
import { Route } from 'react-router-dom';
const PrivateRoute = ({ component: Component, ...rest}) => {
<Route {...rest} render = {() => (
/* I NEED TO CHECK IF USER IS SIGNED IN. HOW DO I ACCESS this.state.signedIn from within the Provider class? */
)} />
}
export default PrivateRoute
我正在开发一个在访问路由之前需要身份验证的组件,但首先我需要弄清楚如何将状态从 Provider 类拉入 PrivateRoute.js
1个回答
您可以将
PrivateRoute
包装在另一个使用 context 作为渲染 prop 的匿名函数中,并通过类似
import React from 'react';
import { Route } from 'react-router-dom';
const PrivateRoute = ({ component: Component, context, ...rest}) => {
return <Route {...rest} render = {() => (
/* use `context.signedIn` from within the Provider class? */
)} />
}
export default () => <Consumer>{(context) => <PrivateRoute context={context} />}</Consumer>
的 props 将其传递给 PrivateRoute。
或者,如果您使用的是
v16.8.0 或更高版本的 react
,则可以使用
useContext
钩子
import React, { useContext } from 'react';
import { Route } from 'react-router-dom';
const PrivateRoute = ({ component: Component, context, ...rest}) => {
const context = useContext(AuthContext);
return <Route {...rest} render = {() => (
/* use `context.signedIn` from within the Provider class? */
)} />
}
Shubham Khatri
2019-04-22