Javascript 如何将变量传递给不同的函数
我是新的反应!但这是 我创建了一个使用JSON url的组件,然后在一个非常被动的组件中输出新闻提要Javascript 如何将变量传递给不同的函数,javascript,reactjs,spfx,Javascript,Reactjs,Spfx,我是新的反应!但这是 我创建了一个使用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(pos
// 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将确保它的纯粹性和可测试性)
然后,在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])
.......
你不能调用这个函数吗<代码>.get(“https://cors-anywhere.herokuapp.com/“+this.getCompanyUrl())。当然,您还需要从
getCompanyUrl
函数返回url
。这是个好主意!!!TY@applepeaperson发布答案我会接受:)你也可以在getCompanyUrl()
中设置url的状态,然后在getPosts()中使用它,很抱歉我是新手,我该如何在getCompanyUrl中设置url的状态?你创建一个状态变量调用url,并在getCompanyUrl的末尾使用它()
console.log()
setState({url,url}),然后在getPosts()中有get('https://cors-anywhere.herokuapp.com/“+this.state.url)
但是如果您在下拉列表的不变函数中执行此操作,那么它将是非常理想的,这样您就不必创建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])
.......