【问题标题】:Return Value from a function in a utils file to the state in react component从 utils 文件中的函数返回值到反应组件中的状态
【发布时间】:2020-01-18 06:05:29
【问题描述】:

我正在尝试重构我的函数,以一种干净的方式将它们模块化。我需要从我的函数中获取返回值,并将它们分别分配给我的组件中的一个状态。这些函数已经在控制台中调用并记录了值(我正在使用 axios)。但它没有设置状态,我无法将值呈现到屏幕上。

export const getWalletBalance = token => {
  let Amount = '';
  console.log('get wallet balance');
  axios
    .get(`${Routes.walletBalance}`, {headers: {token: token}})
    .then(async res => {
      console.log(res);
      return await (Amount = res.data.value.response);
    })
    .catch(err => {
      return console.log(err.response);
    });
  return Amount;
};

这是设置状态

            this.setState({Amount: getWalletBalance(token)});

我应该使用异步/等待吗?

【问题讨论】:

    标签: javascript reactjs react-native


    【解决方案1】:

    在您的代码中,您将异步编程模式 async/await 和 Promise 混为一谈,而对已解析的值不做任何事情。

    由于异步编程的工作原理,您在您的承诺有机会解决之前返回空字符串。

    执行顺序如下:

    1. let Amount = ''
    2. Promise 开始异步执行
    3. 返回空字符串''的值

    您还对 async/await 的使用不正确。

    服务

    export const getWalletBalance = token => {
      return axios
        .get(`${Routes.walletBalance}`, { headers: { token: token } })
        .then(res => {
          return res.data.value.response;
        });
    };
    

    在下面,您可以使用 promises 实现或 async/await 实现。

    承诺实现

    class Page extends React.Component {
      constructor() {
        this.state = {
          token: '<token>',
          Amount: null
        };
      }
    
      // Implementation with promises
      componentDidMount() {
        getWalletBalance(this.state.token)
          .then((balance) => {
            this.setState({ Amount: balance });
          })
      }
    
      render() {
        return (
          <p>
            {this.state.Amount}
          </p>
        );
      }
    }
    

    异步/等待实现

    class Page extends React.Component {
      constructor() {
        this.state = {
          token: '<token>',
          Amount: null
        };
      }
    
      // Implementation with async/await
      async componentDidMount() {
        const balance = await getWalletBalance(this.state.token)
        this.setState({ Amount: balance });
      }
    
      render() {
        return (
          <p>
            {this.state.Amount}
          </p>
        );
      }
    }
    

    【讨论】:

      【解决方案2】:
      export const getWalletBalance = token => {
      
        return axios
          .get(`${Routes.walletBalance}`, {headers: {token: token}})
          .then(async res => {
            return res.data.value.response; // return your amount direct
          })
          .catch(err => {
            return 0; // return your amount direct
            console.log(err.response);
          });
      };
      

      你可以像这样访问它

      将此调用放在异步函数中,以便您可以使用等待

      let Amount = await getWalletBalance(token);
      this.setState({ Amount });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-29
        • 2016-04-07
        • 1970-01-01
        • 1970-01-01
        • 2021-08-25
        • 1970-01-01
        • 2023-03-30
        相关资源
        最近更新 更多