这是我的目标。我想创建一个复合组件,它将在显示children
元素之前检查匹配 url 的有效性。否则,它会返回一个通用组件以显示错误消息。
所以这是我的“装饰器”代码:
const EnforceUrlValidation = (test, children) => {
const fn = ({ match }) => {
if (! test( match )) {
return ( <InvalidUrlContainer /> );
}
return ({children});
}
return fn;
}
这是它在我的路由器中的使用方式:
const WelcomePage = EnforceUrlValidation(
(match) => {
const articleId = match.params.articleId;
return articleId && isValidarticleId(articleId);
}
, <WelcomeContainer/>
)
...
<Routers>
<Switch>
<Route
path="/:articleId"
component={WelcomePage}
/>
...
</Routers>
我现在遇到的问题是我仍然想将match
对象传递到children
inside EnforceUrlValidation
。我怎样才能做到这一点?
尝试 1:
const EnforceUrlValidation = (test, children) => {
const fn = ({ match }) => {
if (! test( match )) {
return ( <InvalidUrlContainer /> );
}
return (<children match={match} />);
}
return fn;
}
在这种children
情况下不呈现。
尝试 2:
const EnforceUrlValidation = (test, children) => {
const fn = ({ match }) => {
if (! test( match )) {
return ( <InvalidUrlContainer /> );
}
return (
<div match={match} >{children} </div>
)
}
return fn;
}
失败是因为div
不支持match