【问题标题】:Render 'async' function return value in render method (React)在渲染方法(React)中渲染“异步”函数返回值
【发布时间】:2021-04-05 16:03:02
【问题描述】:

我正在尝试从我的 react 应用程序中的 async 函数呈现一个简单的返回值,但是每次我尝试整个应用程序时都不会呈现。在不调用该函数的情况下,我的应用程序可以正常呈现。此外,如果我在函数中 console.log 我的返回值(结果),它会在控制台上返回正确的值,但应用程序中没有任何内容呈现。有什么想法吗?

class TitleCards extends Component {
    constructor(props){
        super(props)
        this.totalPortfolio = this.totalPortfolio.bind(this);
        this.getIntradayPrice = this.getIntradayPrice.bind(this);

    }

    async getIntradayPrice(tick) {
        const resp = await fetch(`${IEX.base_url}/stock/${tick}/intraday-prices?chartLast=1&token=${IEX.api_token}`);
        return resp.json();
      }

    async totalPortfolio() {
        const respPromises = this.props.info.map(({ tick }) => this.getIntradayPrice(tick));
        const respArrays = await Promise.all(respPromises);
        console.log(respArrays);
        const result = respArrays.reduce((acc, val, index) => acc + val[0].close * this.props.info[index].amtPurch, 0)
        console.log(result);
        return result;
      }
      
    render(){  
        return(
            <div className="positioning">
                <div className="StockCardTitle">
                    <img src={Folder} className="StockCardTitle-image" /> 
                    {this.totalPortfolio()}
                </div>
            </div>
        )
    }
}

export default TitleCards;

【问题讨论】:

  • React 组件和生命周期是 100% 同步的,尤其是 render 方法。 render 方法也被认为是纯函数,这意味着它应该具有零副作用,例如获取数据。以上 sn-p 中的this.portfolio 是什么?您能否提供一个更完整的代码示例,以便我们了解portfolio 函数是什么以及调用getIntradayPricetotalPortfolio 是什么?
  • 所以我只是添加了完整的组件代码。道具是从另一个组件传入的,但它们是简单的数组。主要问题是渲染一个我不知道该怎么做的异步函数值。我在原始代码 sn-p 中也有一个错误(投资组合函数应该是 totalPortfolio)它已被纠正

标签: javascript reactjs function render


【解决方案1】:

问题

React 组件和生命周期是 100% 同步的,尤其是 render 方法。 render 方法也被认为是一个纯函数,这意味着它应该有零副作用(比如获取数据!!)。

解决方案

您应该重构您的代码以获取componentDidMountcomponentDidUpdate 之一或两者中的数据,并将结果保存到本地组件状态以进行渲染。

这是一个重构示例。

class TitleCards extends Component {
  constructor(props){
    super(props);

    state = {
      portfolioTotal: '',
    };

    this.totalPortfolio = this.totalPortfolio.bind(this);
    this.getIntradayPrice = this.getIntradayPrice.bind(this);
  }

  async getIntradayPrice(tick) {
    const resp = await fetch(`${IEX.base_url}/stock/${tick}/intraday-prices?chartLast=1&token=${IEX.api_token}`);
    return resp.json();
  }

  async totalPortfolio() {
    const { info } = this.props;
    const respPromises = info.map(({ tick }) => this.getIntradayPrice(tick));
    const respArrays = await Promise.all(respPromises);
    const result = respArrays.reduce((acc, val, index) => acc + val[0].close * info[index].amtPurch, 0)
    return result;
  }

  // When the component mounts, call totalPortfolio
  componentDidMount() {
    this.totalPortfolio()
      .then(portfolioTotal => {
        this.setState({
          portfolioTotal
        });
      })
      .catch(error => {
        // add any required error handling/messaging here
      });
  }

  render() {
    const { portfolioTotal } = this.state;
    return(
      return(
        <div className="positioning">
          <div className="StockCardTitle">
            <img src={Folder} className="StockCardTitle-image" /> 
            {portfolioTotal} // <-- render state value
          </div>
        </div>
    );
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 1970-01-01
    • 2022-11-23
    • 2021-12-09
    • 1970-01-01
    相关资源
    最近更新 更多