当涉及到react/react router 4时,我显然不理解这里的某些内容。我正在尝试检查用户是否已登录或注销,以控制导航栏用户状态路由。我好像无法接触到道具,它就这么消失了。有人能指出我不理解的地方吗?isUserLoggedInServerCheck在服务器端返回一个值,然后在AppServer端返回一个值,然而在CandidateLanding端它返回未定义的值。
路径:Server
onPageLoad(sink => {
let isUserLoggedInServerCheck = false;
if (sink.request.cookies.sssr) {
isUserLoggedInServerCheck = true;
}
sink.renderIntoElementById(
'react-target',
renderToString(
<AppServer
location={sink.request.url}
isUserLoggedInServerCheck={isUserLoggedInServerCheck}
/>
)
);
});路径:AppServer
const AppServer = props => {
const context = {};
const { location, isUserLoggedInServerCheck } = props;
return (
<StaticRouter context={context} location={location} isUserLoggedInServerCheck={isUserLoggedInServerCheck}>
<div className="application">
<Switch>
<Route path="/" exact component={CandidateLanding} />
</Switch>
</div>
</StaticRouter>
);
};路径:CandidateLanding
function CandidateLanding(props) {
const { location, isUserLoggedInServerCheck } = props;
return (
<div>
<Navbar location={location.path} isUserLoggedInServerCheck={isUserLoggedInServerCheck} />
</div>
);
}
const CandidateLandingContainer = withTracker(props => {
const { isUserLoggedInServerCheck } = props;
if (Meteor.isServer) {
return {
isUserLoggedInServerCheck
};
}
if (Meteor.isClient) {
return {
isUserLoggedInServerCheck
};
}
})(CandidateLanding);发布于 2019-06-01 14:22:26
您正在将您的道具传递给StaticRouter,而它们永远不会到达CandidateLanding组件。执行此操作的最佳方法是对路径使用render函数
<Route path="/" exact render={ (props) => <CandidateLanding {...props} anotherProp={ anotherVariable } />} />确保也从静态路由器中删除了不必要的道具。Source
发布于 2019-06-01 14:32:28
StaticRouter不会向其子级提供属性isUserLoggedInServerCheck。实现这一点的一种方法是使用react上下文。这避免了将参数从一个主管传递到下一个主管的要求。要使用上下文,您将需要一个上下文实例,对提供者<UserLoggedInContext.Provider value={isUserLoggedInServerCheck}>执行const UserLoggedInContext = React.createContext();操作,最后对使用者(useContext) const isUserLoggedInServerCheck = React.useContext(UserLoggedInContext);执行const UserLoggedInContext = React.createContext();操作,以在需要的位置获取所提供的值。
示例
const UserLoggedInContext = React.createContext();
const AppServer = props => {
const context = {};
const { location, isUserLoggedInServerCheck } = props;
return (
<UserLoggedInContext.Provider value={isUserLoggedInServerCheck}>
<StaticRouter context={context} location={location} >
<div className="application">
<Switch>
<Route path="/" exact component={CandidateLanding} />
</Switch>
</div>
</StaticRouter>
</UserLoggedInContext.Provider>
);
};
// ...
function CandidateLanding(props) {
const { location } = props;
return (
<div>
<Navbar location={location.path} />
</div>
);
}
const CandidateLandingContainer = withTracker(props => {
const isUserLoggedInServerCheck = React.useContext(UserLoggedInContext);
if (Meteor.isServer) {
return {
isUserLoggedInServerCheck
};
}
if (Meteor.isClient) {
return {
isUserLoggedInServerCheck
};
}
})(CandidateLanding);欲了解更多详情,请访问:react context
https://stackoverflow.com/questions/56404045
复制相似问题