gpt4 book ai didi

javascript - React-Router - 在路由数组映射外使用 时出错

转载 作者:行者123 更新时间:2023-11-30 14:11:06 26 4
gpt4 key购买 nike

我正在使用 React 路由器从数组动态生成路由。如果没有匹配的路径,那么我希望显示一个 404 页面。

我遇到的问题是,当用 <Switch> 包装数组映射时,我在控制台中看到以下错误。 :

Warning: React does not recognize the computedMatch prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase computedmatch instead. If you accidentally passed it from a parent component, remove it from the DOM element.

请在下面查看我的代码示例:

const sections = [
'section1',
'section2',
'section3'
];

<Switch>

{/* If only /section/ is loaded in the browser, redirect to the first section */}
<Route exact path="/section" render={() => (
<Redirect to="/section1/home" />
)}/>

{/* Map through the sections array */}
{this.state.sections.map((section, sectionIndex) => (
<div key={sectionIndex}>
<Route path={"/section/" + section + "/home"} render={() => (
<Section
testProp={'test'}
/>
)}/>
</div>
))}

{/* 404 Page */}
<Route component={NoMatch} />

</Switch>

如果我手动将这些部分创建为单独的 <Route>组件,然后包装一个 <Switch>在它们周围,错误不存在,所以我认为这与数组映射有关。

我无法手动创建所有部分,因为我们最终可能会有数百个部分需要路线路径。我还需要能够将多个 Prop 发送到 <Section>组件,这就是我使用 render() 的原因 Prop <Route>

我可能在这里遗漏了一些简单的东西。任何人都可以请教吗?非常感谢。

最佳答案

我认为您需要使用 match在您的网址中,因为这些部分是相同的,唯一的区别是名称。

考虑使用一个带有 Container 的单一路由加载您的部分:

<Switch>
<Route exact path="/section/:section/home" component={SectionContainer} />
<Route component={NotFoundPage} />
</Switch>

SectionContainer您可以访问 section来自 url如下:

const { section } = this.props.match.params;

const activeSection = this.props.match.params.section;

因此您将能够从您的后端获取此部分的信息。

此外,如果您需要将一些新的 Prop 传递给您的容器,您可以这样做:

const SpecialSectionContainer= (props) => (
<SectionContainer
special="this section is special"
{...props}
/>
);

然后 <Route exact path="/section/:section/special/home" component={SpecialSectionContainer} /> .

一旦进入你的 Container 部分,你就可以切换你已知的部分来加载适当的函数,如果使用像 redux 这样的状态管理 API,你的 reducer/saga 将根据加载部分。

希望能解决您的问题。

问候。

编辑

例如,使用 redux ,您可以执行以下操作:

componentWillMount = () => {
this.props.loadSection(this.props.match.params.section);
};

这将调度一个将被您的副作用中间件(基本上是 thunk 或 saga)拦截的操作,并将执行 API 调用以获取您的数据并将其存储在 store 中。 .和你的 SectionContainer最终将轻松加载它们并将它们传递给功能组件 just display them .

关于javascript - React-Router - 在路由数组映射外使用 <Switch> 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54439419/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com