我正在使用上下文API在React应用程序中进行状态管理,并且正在寻找一种方法来从我的Provider类中访问无状态函数中的状态。
我熟悉将Consumer标签围绕在render()中的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 (提供程序类)
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
答案 0 :(得分:1)
您可以将PrivateRoute
包裹在另一个匿名函数中,该匿名函数使用上下文作为渲染道具并将其通过诸如这样的道具传递给PrivateRoute
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>
或者如果您使用的是 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? */
)} />
}