Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 渲染';异步';渲染方法中的函数返回值(React)_Javascript_Reactjs_Function_Render - Fatal编程技术网

Javascript 渲染';异步';渲染方法中的函数返回值(React)

Javascript 渲染';异步';渲染方法中的函数返回值(React),javascript,reactjs,function,render,Javascript,Reactjs,Function,Render,我试图在react应用程序中呈现一个来自async函数的简单返回值,但是每次我尝试呈现整个应用程序时,都不会呈现。不调用函数,我的应用程序呈现良好。另外,如果我在函数中记录我的返回值(result),它会在控制台上返回正确的值,但应用程序中不会显示任何内容。知道发生了什么事吗 class TitleCards extends Component { constructor(props){ super(props) this.totalPortfolio =

我试图在react应用程序中呈现一个来自
async
函数的简单返回值,但是每次我尝试呈现整个应用程序时,都不会呈现。不调用函数,我的应用程序呈现良好。另外,如果我在函数中记录我的返回值(result),它会在控制台上返回正确的值,但应用程序中不会显示任何内容。知道发生了什么事吗

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;
类标题扩展组件{
建造师(道具){
超级(道具)
this.totalPortfolio=this.totalPortfolio.bind(this);
this.getIntradayPrice=this.getIntradayPrice.bind(this);
}
异步getIntradayPrice(勾号){
const resp=wait fetch(`${IEX.base_url}/stock/${tick}/intraday prices?chartLast=1&token=${IEX.api_token}`);
返回resp.json();
}
异步totalPortfolio(){
const respromises=this.props.info.map(({tick})=>this.getIntradayPrice(tick));
const resprays=等待承诺。全部(resprownes);
console.log(resp数组);
const result=resparies.reduce((acc,val,index)=>acc+val[0]。关闭*this.props.info[index]。amtpourch,0)
控制台日志(结果);
返回结果;
}
render(){
返回(
{this.totalPortfolio()}
)
}
}
导出默认标题栏;
问题
React组件和生命周期是100%同步的,尤其是
render
方法。
render
方法也被认为是一个纯函数,这意味着它应该没有任何副作用(比如获取数据!!)

解决方案 您应该重构代码以获取
componentDidMount
componentdiddupdate
中的一个或两个中的数据,并将结果保存到本地组件状态以进行渲染

下面是一个重构示例

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>
    );
  }
}
类标题扩展组件{
建造师(道具){
超级(道具);
状态={
门户网站:,
};
this.totalPortfolio=this.totalPortfolio.bind(this);
this.getIntradayPrice=this.getIntradayPrice.bind(this);
}
异步getIntradayPrice(勾号){
const resp=wait fetch(`${IEX.base_url}/stock/${tick}/intraday prices?chartLast=1&token=${IEX.api_token}`);
返回resp.json();
}
异步totalPortfolio(){
const{info}=this.props;
const respromises=info.map(({tick})=>this.getIntradayPrice(tick));
const resprays=等待承诺。全部(resprownes);
const result=resparies.reduce((acc,val,index)=>acc+val[0]。关闭*info[index]。amtpourch,0)
返回结果;
}
//当组件挂载时,调用totalPortfolio
componentDidMount(){
这个.totalPortfolio()
.然后(Portfoliotottal=>{
这是我的国家({
Portfoliotottal
});
})
.catch(错误=>{
//在此处添加任何所需的错误处理/消息
});
}
render(){
const{portfoliotottal}=this.state;
返回(
返回(

{Portfoliotottal}//React组件和生命周期是100%同步的,尤其是
render
方法。
render
方法也被认为是一个纯函数,这意味着它应该没有任何副作用,比如获取数据。在上面的代码片段中,
这个.portfolio
是什么?你能提供一个更完整的代码示例,让我们看看它是什么吗t
portfolio
函数是,调用的是什么
getIntradayPrice
totalPortfolio
?所以我刚刚添加了完整的组件代码。道具是从另一个组件传入的,但它们是简单的数组。主要问题是呈现一个异步函数值,我不知道如何做。此外,我在ori中有一个错误ginal代码片段(公文包函数本来是totalPortfolio)已更正