Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/437.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.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 在.map的最后一次迭代中调用函数_Javascript_Reactjs - Fatal编程技术网

Javascript 在.map的最后一次迭代中调用函数

Javascript 在.map的最后一次迭代中调用函数,javascript,reactjs,Javascript,Reactjs,我想执行道具在映射循环的最后一次迭代中接收到的函数 我试图在index等于array.length-1时执行该函数,但每次迭代时它仍会执行该函数,因此每次迭代时都会出现console.log(“last index”) 其思想是在每次迭代中增加totalPrice后,以totalPrice作为参数执行this.props.HandletTotalPrice 我尝试了以下代码: products&&products.map((产品,索引)=>{ const cost=Math.round((pro

我想执行道具在映射循环的最后一次迭代中接收到的函数

我试图在index等于array.length-1时执行该函数,但每次迭代时它仍会执行该函数,因此每次迭代时都会出现console.log(“last index”)

其思想是在每次迭代中增加totalPrice后,以totalPrice作为参数执行this.props.HandletTotalPrice

我尝试了以下代码:

products&&products.map((产品,索引)=>{
const cost=Math.round((product.price*planningData[product.productId][planningType])*100)/100;
nbCount+=parseInt(planningData[product.productId][planningType]);
总价+=成本;
如果(索引===products.length-1){
console.log(“最后一个索引”)
此.props.handleTotalPrice(总价)
}
});

最有效的方法是在映射完成后执行回调,而不是在最后一次迭代时执行回调

{products && products.map((product, index) => {
       const cost = Math.round((product.price * planningData[product.productId][planningType]) * 100) / 100;
       nbCount += parseInt(planningData[product.productId][planningType]);
       totalPrice += cost;
}) && this.props.handleTotalPrice(totalPrice);
注:

  • 使用
    Array.map
    而不在回调中返回任何内容与使用
    Array.forEach
在React中编写JSX 通常建议只在
render
函数中执行简单操作,不建议在render函数中使用回调函数(如
handleTotalPrice
),这可能会导致错误或严重的性能问题

假设您使用的是支持挂钩的React版本,我会对代码进行如下更改:

const MyComponent({ handleTotalPrice }) {
    const products = {/* your data*/};

    // Compute total price outside render function
    // Use `useMemo` so price is only recalculated if products list changes
    const totalPrice = useMemo(() => {
       if (!products) return 0;

       const total = products.reduce((sum, product) => {
           const cost = Math.round((product.price * planningData[product.productId][planningType]) * 100) / 100;
           return sum + cost;
       });

       // Call the callback when price changes
       handleTotalPrice(total);
    }, [products]);

    // Render
    return <div>
       {totalPrice}
    </div>;
}
const MyComponent({handleTotalPrice}){
const products={/*您的数据*/};
//计算渲染函数之外的总价格
//使用“useMemo”,这样只有在产品列表发生变化时才重新计算价格
const totalPrice=useMoom(()=>{
如果(!products)返回0;
const total=乘积。reduce((总和,乘积)=>{
const cost=Math.round((product.price*planningData[product.productId][planningType])*100)/100;
退货金额+成本;
});
//当价格变化时调用回调
handleTotalPrice(总计);
},[产品];
//渲染
返回
{totalPrice}
;
}

因为您可以使用
reduce
而不是
map
迭代地运行一个求和,然后返回值,并对结果进行处理

products &&
  this.props.handleTotalPrice(
    products.reduce((totalPrice, product) => {
        const cost = Math.round((product.price * planningData[product.productId][planningType]) * 100) / 100;
        nbCount += parseInt(planningData[product.productId][planningType]);
        totalPrice += cost;
        return totalPrice;
      }, 0)
    )

如果你没有在地图内部返回,考虑使用<代码>前缀 >下面有代码,所以我需要在渲染函数内部不改变状态,更不用说JSX了。我不认为它在每次迭代时都执行函数;如果您看到大量的
last index
console条目,那是因为您正在创建一个无限渲染->状态更改->渲染loop@Versifiction您的代码不保存地图。它只是把地图作为一种先兆,你需要完全改变你的方法;每当产品的数据发生更改时,计算总成本,而不是在render方法中。它在JSX中,我不能将“&&this.props.handleTotalPrice(totalPrice);”直接添加到否之后?@versionfiction在这种情况下,最好将其移动到名为
renderProducts
”的单独函数中,因为它将更高效,也更容易阅读/维护。这是一种不好的做法;您不应该将这样的计算放在JSX中,更不用说函数调用了。@versify请查看我的编辑,了解有关编写JSX和反应代码的更好方法的更多说明。