当涉及到对路由器4的反应/反应时,我显然不了解这里的内容。我试图检查用户是否已登录或注销以控制navbar用户状态路由。我似乎无法访问道具,它消失了。有人可以指出我不了解的内容吗? isUserLoggedInServerCheck
在Server处返回一个值,然后在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);
答案 0 :(得分:0)
您正在将道具传递给StaticRouter
,但它们从未传递给CandidateLanding
组件。最好的方法是对路径使用render函数
<Route path="/" exact render={ (props) => <CandidateLanding {...props} anotherProp={ anotherVariable } />} />
确保还要从“静态路由器”中删除不必要的道具。 Source
答案 1 :(得分:0)
StaticRouter
不会向其子级提供属性isUserLoggedInServerCheck
。实现此目的的一种方法是使用反应上下文。这避免了将参数从一个主管传递到下一个的要求。要使用上下文,您将需要一个上下文实例,const UserLoggedInContext = React.createContext();
提供者<UserLoggedInContext.Provider value={isUserLoggedInServerCheck}>
,最后是使用者(useContext)const isUserLoggedInServerCheck = React.useContext(UserLoggedInContext);
才能在需要的地方获得所提供的值。
示例
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