关于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"
}
答案 0 :(得分:1)
我想您几乎已经发布了示例代码。您已经在所有数据上进行映射以创建新的<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>
);
}
}