我不是100%的术语。随时纠正/通知。
因此,我安装了此组件并执行数据获取。所有子路由均取决于此数据。很好。
它们还取决于特定的参数characterId
。在我的子路线的组件中确定默认参数很容易。
但是如何在不使用characterId
参数的情况下进行路由?
此刻,如果没有为下面的父组件提供characterId
,我将从fetch响应中选择一个,以便我可以重定向(替换当前历史记录项)以及在render()中渲染子路由时( ),则找到匹配项。
示例代码。我去除了边缘上的很多绒毛,使其尽可能清晰。
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
class DisplayProfile extends React.Component {
constructor(props) {
super(props);
this.state = {};
this.fetch = this.fetch.bind(this);
}
fetch = () => {
return fetch(`https://www.bungie.net/Platform/Destiny2/${this.props.match.params.membershipType}/Profile/${this.props.match.params.membershipId}/?components=100,104,200,202,204,205,800,900`)
.then(response => {
return response.json();
})
.catch(error => {
console.log(error);
});
};
componentDidMount() {
this.fetch()
.then(ProfileResponse => {
if (!ProfileResponse.Response.characterProgressions.data) {
throw new SyntaxError('privacy');
}
let route = this.props;
let characterId = ProfileResponse.Response.characters.data.filter(character => character.characterId === route.match.params.characterId).length === 1 ? route.match.params.characterId : ProfileResponse.Response.characters.data[0].characterId;
let view = route.match.params.view;
if (!route.match.params.characterId || ProfileResponse.Response.characters.data.filter(character => character.characterId === route.match.params.characterId).length < 1) {
if (route.match.params.characterId) {
view = route.match.params.characterId;
}
}
let primary = route.match.params.primary;
let secondary = route.match.params.secondary;
let tertiary = route.match.params.tertiary;
let quaternary = route.match.params.quaternary;
// i hate this
route.history.replace(`/progression/${route.match.params.membershipType}/${route.match.params.membershipId}/${characterId}${view ? `/${view}` : ``}${primary ? `/${primary}` : ``}${secondary ? `/${secondary}` : ``}${tertiary ? `/${tertiary}` : ``}${quaternary ? `/${quaternary}` : ``}`);
this.setState({
ProfileResponse: ProfileResponse.Response
});
})
.catch(error => {
this.setState({
error: error.message
});
});
}
render() {
if (this.state.ProfileResponse) {
return (
<Route
path="/progression/:membershipType/:membershipId/:characterId/:view?/:primary?/:secondary?/:tertiary?/:quaternary?"
render={route => (
<Route path="/progression/:membershipType/:membershipId/:characterId" exact render={() => <Summary state={this.state} manifest={this.props.manifest} route={route} />} />
<Route path="/progression/:membershipType/:membershipId/:characterId/collections/:primary?/:secondary?/:tertiary?/:quaternary?" render={() => <Collections state={this.state} manifest={this.props.manifest} viewport={this.props.viewport} route={route} />} />
)}
/>
);
}
}
}