我知道如何做到这一点,但我想问一下是否有更好的方法?我有一个在两条不同路线上完全相同的组件,唯一改变的是其中的组件。看起来像这样。
/conjugation/config/:id
/conjugation/quiz
如您所见,它们都是相同的,目前我为它们提供了两个组件,用于渲染包装器和其中的组件。但是,我可以在两个组件 QuizCard
和 ConfigCard
之间共享包装器,并根据路由更改任何布局:
方式一:
const Conjugation = (props) => {
const {match} = props;
return (
<>
<Route exact path={`${match.url}/`} component={HowTo}/>
<Route path={[match.url + "/config/:id", match.url + "/quiz"]}>
<PageWrapper>
<Route path={`${match.url}/config/:id`} component={ConfigCard}/>
<Route exact path={`${match.url}/quiz`} component={QuizCard} />
</PageWrapper>
</Route>
<SvgWaveTop />
<QuizSelectSideBar />
</>
)
}
其中 Config and Quiz 卡片被包裹在一个 Wrapper 组件(styled-components)中,这是一个带有橙色边框的框...
方式二:
const Conjugation = (props) => {
const {match, location} = props;
const relativePath = location.pathname.replace(match.path, "");
return (
<>
<Route exact path={`${match.url}/`} component={HowTo}/>
<Route path={[match.url + "/config/:id", match.url + "/quiz"]}>
<PageWrapper>
<MainCardContainer relativePath={relativePath}>
<Route path={`${match.url}/config/:id`} component={ConfigCard}/>
<Route exact path={`${match.url}/quiz`} component={QuizCard} />
</MainCardContainer>
</PageWrapper>
</Route>
<SvgWaveTop />
<QuizSelectSideBar />
</>
)
}
道具“relativePath”决定了给定路径的样式,这里有一个switch语句。 MainCardContainer 是带有橙色边框的框,只是为了澄清。
我的问题是,是否值得采用方式 2,或者我应该保持简单并采用方式 1?做方式 2 是否意味着 Wrapper "MainCardContainer" 在从 config 路由更改为 quiz 路由时不会重新渲染?