简体   繁体   English

Axios请求使用包含映射集合中的变量的URL

[英]Axios request using URL that includes a variable from a mapped collection

I don't think the title does a good job explaining this, so I'm sorry about that. 我认为标题不能很好地解释这一点,所以对此我感到抱歉。 Here's the quick summary. 这是快速摘要。 I have a collection that includes a key I need to pull out and append to a URL for an axios.get request. 我有一个包含密钥的集合,我需要拔出该密钥并将其附加到axios.get请求的URL上。 But, I need to map over the collection and make a get request for each key and return the results for each key. 但是,我需要映射集合,并为每个键提出一个get请求,并返回每个键的结果。

If that doesn't make sense, maybe my terrible code will: 如果那没有道理,也许我糟糕的代码将:

return this.props.wallets.map(wallet => {

  const apiLink = "https://api.smartbit.com.au/v1/blockchain/address/";
  const key = wallet.publicKey;
  const url = apiLink + key;
  this.getData = () => {
    axios
    .get(
      url
    )
    .then(res => {
      this.setState({ coins: res.data.address.total.received_int });
    })
    .catch(error => {
      console.log(error);
    });
  };

  let totalBitcoin = this.state.coins/100000000;

    return (
      <tr key={wallet._id}>
        <td>
          <Link className="wallet-link" to={link}>
            {wallet.title}
            <span className="glyphicon glyphicon-stats" />
          </Link>
        </td>
        <td>
          {totalBitcoin}
        </td>
        <td>
          <Link to="/wallets/delete">
            <span className="glyphicon glyphicon-trash" />
          </Link>
        </td>
      </tr>
  );
});

getData is a function that makes sure I'm only making the get request at a predetermined interval. getData是确保我仅在预定时间间隔发出get请求的函数。

So, this almost works. 因此,这几乎可行。 I get the data back, sets all instances in my table of the totalBitcoin variable with the same result. 我取回数据,并在表中设置totalBitcoin变量的所有实例,结果相同。 Then it constantly updates that value as the function maps through my collection. 然后,随着函数通过我的集合进行映射,它会不断更新该值。

I have no idea how to make this axios request without mapping over my collection to get the necessary variable for the endpoint I'm calling. 我不知道如何在不映射我的集合的情况下发出此axios请求,以获取我正在调用的端点的必要变量。 And I have no idea how to properly set my mapped variable. 而且我不知道如何正确设置映射变量。 Any help would be so appreciated. 任何帮助将不胜感激。

You are invoking this.setState method inside every iteration of this.props.wallets.map , this.state.coins value is constantly being reseted to a new value upon every axios request resolvement. 您在this.setState每次迭代中都调用this.setState方法,每次axios请求this.props.wallets.mapthis.state.coins值会不断this.state.coins为新值。 This seems useless. 这似乎没用。 Also the variable totalBitcoin will always be equal to the last resolved wallet's axios response res.data.address.total.received_int . 同样,变量totalBitcoin将始终等于最后解析的钱包的axios响应res.data.address.total.received_int

You could do the API calls in the componentDidMount() , then append each wallet response to the this.wallets array like so this.setState({wallets: [...this.state.wallets, wallet]}) . 您可以在componentDidMount()进行API调用,然后将每个钱包响应追加到this.wallets数组,例如this.setState({wallets: [...this.state.wallets, wallet]}) Now in the render function you can do return.this.state.wallet.map(wallet => ...) ; 现在在render函数中,您可以return.this.state.wallet.map(wallet => ...) ;

Example

  class WalletContainer extends React.Component {
    componentDidMount(){
      this.props.wallets.map(wallet => {
        const apiLink ="https://api.smartbit.com.au/v1/blockchain/address/";
        const key = wallet.publicKey;
        const url = apiLink + key;
        this.getData = () => {
          axios
          .get(
            url
          )
          .then(res => {
            const newWallet = { 
                id: wallet._id,
                title: wallet.title,
                coins: res.data.address.total.received_int
            }
            this.setState({ wallets:
              [...this.state.wallets, newWallet]
             });
          })
          .catch(error => {
            console.log(error);
          });
        };
      })
    }
    render(){
      return this.state.wallets.map(wallet => {
        const totalBitcoin = wallet/100000000; // should be const because it never changes
        return (
          <tr key={wallet.id}>
            <td>
              <Link className="wallet-link" to={link}>
                {wallet.title}
                <span className="glyphicon glyphicon-stats" />
              </Link>
            </td>
            <td>
              {totalBitcoin}
            </td>
            <td>
              <Link to="/wallets/delete">
                <span className="glyphicon glyphicon-trash" />
              </Link>
            </td>
          </tr>
        );
      })
    }

  }

in case it's possible for props to change, you should write additional logic in willRecieveProps() where you will do the axios request and append the new wallet to the this.state.wallets or remove a wallet that is not present in the new props. 如果道具可能发生变化,则应该在willRecieveProps()中编写其他逻辑,在该处您将执行axios请求并将新的钱包追加到this.state.wallets或删除新道具中不存在的钱包。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM