来自查询的 React 路由的 if 语句



我有以下关于 React 和 React 路由的问题。 我正在尝试根据从查询返回的国家/地区和项目进行路由。基本上,我相信我需要一个 if 语句来查看每个标题的_id是项目还是国家,以便返回正确的相应组件(RenderCountry 或 RenderProject(。

componentDidMount() {
client
.fetch('*[_type == "land" || _type =="project"] {title, slug, _type }')
.then(country => this.setState({ country }));
}
render() {
return (
<Switch>
{this.state.country.map(post => (
<Route
path={`/${post.slug.current}`}
exact
component={RenderCountry}
/>
))}
<Route path="/" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/countries" exact component={Countries} />
<Route path="/projects" exact component={Projects} />
<Route component={FouroFour} />
</Switch>
);
}

期待您的回复! 以下是查询的结果:

{
_type: "land",
slug: {
_type: "slug",
current: "namibia"
},
title: "Namibia"
}
{
_type: "land",
slug: {
_type: "slug",
current: "niger"
},
title: "Niger"
}
{
_type: "project",
slug: {
_type: "slug",
current: "self-help-or-social-transformation"
},
title: "Self help or social transformation"
}
{
_type: "project",
slug: {
_type: "slug",
current: "mozambique-norway-accessibility-partnership"
},
title: "Mozambique/Norway Accessibility Partnership"
}
{
_type: "project",
slug: {
_type: "slug",
current: "matching-education-skills-and-work"
},
title: "Matching education, skills and work"
}

我想你发布的示例代码几乎就在那里了。您已经在映射所有数据以创建新的<Route />组件。在此映射期间,您可以访问_type,因此您可以根据该属性确定要传递给路由的component道具。

像这样:

render() {
return (
<Switch>
{this.state.country.map(post => (
<Route
path={`/${post.slug.current}`}
exact
component={post._type === 'country' ? RenderCountry : RenderProject}
/>
))}
</Switch>
);
}

如果您有不同类型的组件要为每个post._type渲染,最好创建一个映射,因此您将拥有类似以下内容的内容:

const routeComponentMap = {
land: RenderCountry,
project: RenderProject
};
export class RenderRoute extends Component {
constructor() {
super();
this.state = {
country: [],
project: []
};
}
componentDidMount() {
client
.fetch('*[_type == "land" || _type =="project"] {title, slug, _type }')
.then(country => this.setState({ country }));
}
render() {
return (
<Switch>
{this.state.country.map(post => (
<Route
path={`/${post.slug.current}`}
exact
component={routeComponentMap[post._type]}
/>
))}
<Route path="/" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/countries" exact component={Countries} />
<Route path="/projects" exact component={Projects} />
<Route component={FouroFour} />
</Switch>
);
}
}

最新更新