javascript - 反应如何将变量传递给不同的函数
问题描述
我是新来的反应!但是这里...
我创建了一个使用 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 }));
}
我设置了用户将在 UI 中输入 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.
有任何想法吗?!:)
解决方案
首先确保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])
.......
推荐阅读
- c# - C# - 理解对象、类和方法交互
- rust - 如何实现不同内部类型之间的转换?
- python - 为什么我的机器人在加入语音时没有错误?不和谐.py
- python - 从另一个模块访问全局变量
- c - 在C中的矩阵中查找距离
- python - 数据库(字典)中的语法错误(Python)
- javascript - Disney+ 如何防止对其内容进行屏幕录制?
- entity-framework - 光子独立服务器 Unity3D .Net5 问题
- python - 如何将 if 语句应用于列中的每个值并根据该值更新不同的行
- javascript - NODE.JS、Express、mySQL2:在另一个对象中附加一个对象时出现问题