首页 > 解决方案 > 反应如何将变量传递给不同的函数

问题描述

我是新来的反应!但是这里...

我创建了一个使用 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.

有任何想法吗?!:)

标签: javascriptreactjsspfx

解决方案


首先确保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])
    .......

推荐阅读