我是新来的反应者!但是这里...
我创建了一个使用JSON url的组件,然后将新闻订阅源吐出到一个相当被动的组件中。
// Grabs the posts from the json url
public getPosts() {
axios
.get("https://cors-anywhere.herokuapp.com/" + this.props.jsonUrl)
.then(response =>
response.data.map(post => ({
id: `${post.Id}`,
name: `${post.Name}`,
summary: `${post.Summary}`,
url: `${post.AbsoluteUrl}`,
imgUrl: `${post.ListingImageUrl}`
}))
)
.then(posts => {
this.setState({
posts,
isLoading: false
});
})
// We can still use the `.catch()` method since axios is promise-based
.catch(error => this.setState({ error, isLoading: false }));
}
我已设置为用户将在用户界面中键入JSON url,但是现在我需要使其与下拉选择一起使用,因此我创建了一个switch语句来处理此问题。
// This will update the json URL for getPosts
public getCompanyUrl() {
let url: string = '';
switch (this.props.listName) {
case "company1":
url = "http://example1.co.uk";
break;
case 'company2':
url = "http://example2.co.uk";
break;
case 'company3':
url = "http://example3.co.uk";
break;
case 'company4':
url = "http://example4.co.uk";
break;
case 'company5':
url = "http://example5.co.uk";
break;
case 'company6':
url = "http://example6.co.uk";
break;
default:
url = '';
}
console.log(url);
}
我不确定如何更新:
.get("https://cors-anywhere.herokuapp.com/" + this.props.jsonUrl)
使用switch语句的url变量代替this.props.jsonUrl.
有什么想法吗?! :)
答案 0 :(得分:0)
首先确保getCompanyUrl
返回url
的值,并接受listName
参数。 (不直接在此函数内调用props会确保其纯且可测试性更高。)
public getCompanyUrl(listName) {
switch (listName) {
case "company1":
return "http://example1.co.uk";
case 'company2':
return "http://example2.co.uk";
case 'company3':
return "http://example3.co.uk";
case 'company4':
return "http://example4.co.uk";
case 'company5':
return "http://example5.co.uk";
case 'company6':
return "http://example6.co.uk";
default:
throw new Error();
}
}
然后在您的getPosts()
函数中,您可以调用此函数以返回公司的相关URL:
axios
.get(getCompanyUrl(this.props.listName))
.......
或者,您可以通过将getCompanyUrl
转换为键/值对象,然后从那里查找值来简化此操作:
const companies = {
"company1: "http://example1.co.uk",
"company2: "http://example2.co.uk",
"company3: "http://example3.co.uk",
"company4: "http://example4.co.uk",
"company5: "http://example5.co.uk",
"company6: "http://example6.co.uk"
}
axios
.get(companies[this.props.listName])
.......