Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.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 RangeError:数组长度无效_Javascript_Arrays_Reactjs - Fatal编程技术网

Javascript RangeError:数组长度无效

Javascript RangeError:数组长度无效,javascript,arrays,reactjs,Javascript,Arrays,Reactjs,我想从对象上的键中获取数组,但当对象为空时,长度应为0。当我尝试对数组执行console.log()时,数组的长度是正确的,但是我的代码在我的浏览器上抛出以下错误并停止执行: RangeError: invalid array length burger/transformedIngredients< src/components/Burger/Burger.js:8 5 | const burger = (props) => { 6 | let transform

我想从对象上的键中获取数组,但当对象为空时,长度应为0。当我尝试对数组执行
console.log()
时,数组的长度是正确的,但是我的代码在我的浏览器上抛出以下错误并停止执行:

RangeError: invalid array length
burger/transformedIngredients<
src/components/Burger/Burger.js:8

   5 | const burger = (props) => {
   6 |   let transformedIngredients = Object.keys(props.ingredients).map(igKey => (
   7 |     // eslint-disable-next-line max-len,react/no-array-index-key
>  8 |     [...Array(props.ingredients[igKey])].map((_, i) => <BurgerIngredient key={igKey + i} type={igKey} />)
   9 |   )).reduce((arr, el) => (
  10 |     arr.concat(el)
  11 |   ), []);

我真的不明白为什么要对键进行额外的映射并创建多维数组,但如果要为每个键呈现一个成分,可以将代码更改为:

const burger = (props) => {
  let transformedIngredients = Object.keys(props.ingredients).map((igKey, i) => (
    <BurgerIngredient key={igKey + i} type={igKey} />
  ));
}
constburger=(道具)=>{
让transformedIngredients=Object.keys(props.components).map((igKey,i)=>(
));
}

如果其中一种成分的值为负值,则可能发生错误,例如:

state = {
  ingredients: {
    salad: -1, // this will cause the error
    bacon: 0,
    cheese: 0,
    meat: 0,
  },
  totalPrice: 4,
};
您可以通过确保不会在
数组
构造函数中传递负数来防止这种情况,例如,如果负数,您可以传递
0

[...Array(Math.max(0, props.ingredients[igKey]))]

我走的是同一条路,也犯了同样的错误。检查reducer.js文件,并将其与课程中提供的源代码进行比较。在我的例子中,从reducer.js传递的数组与Burger.js接收的数组不匹配。修复reducer.js文件后,错误消失

修复后,我的代码如下所示:

    const reducer = (state = initialState, action) => {
  switch (action.type) {
    case actionTypes.ADD_INGREDIENT:
      return {
        ...state,
        ingredients: {
          ...state.ingredients,
          [action.ingredientName]: state.ingredients[action.ingredientName] + 1
        },
        totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]
      };
    case actionTypes.REMOVE_INGREDIENT:
      return {
        ...state,
        ingredients: {
          ...state.ingredients,
          [action.ingredientName]: state.ingredients[action.ingredientName] - 1
        },
        totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]
      };
    default:
      return state;
    }
    };    

我从同样的课程中学习反应,我和你们有同样的问题。在const Component_PRICES中,所有对象的大小写应与buildcontrols.js中使用的相同,在此const controls中,检查单词与成分_PRICES匹配的上下原因,然后问题将得到解决。

在这种情况下,我通过设置将错误缩小到尝试将价格值传递给查询参数时的错误将Number.parseFloat和tofix固定在价格整数上,从而消除导致字符串化小数的错误

purchaseContinueHandler = () => {            
            const queryParams = [];
            let price = Number.parseFloat(this.state.totalPrice).toFixed(2);

            for (let i in this.state.ingredients) {
                queryParams.push(encodeURIComponent(i) + '=' + encodeURIComponent(this.state.ingredients[i]));
            }
            queryParams.push('price=' + price);

            const queryString = queryParams.join('&'); 

            this.props.history.push({
                pathname: '/checkout',
                search: '?' + queryString
            });


对我来说,这个错误是因为价格值中有一个字符串小数

与您的错误相同,可能的错误是添加配料


通过将复制对象行中的“[]”更改为“{}”,解决了我的问题。我没有注意到我使用了[]。我也犯了同样的错误,将“b”和“c”改为大写 在“培根”和“奶酪”中

通过在相同的情况下使用每个字符,问题得以解决:

const controls=[
  {label:'salad',type:'salad'},
  {label:'bacon',type:'bacon'},
  {label:'cheese',type:'cheese'},
  {label:'meat',type:'meat'}
  ];

我正在学习相同的课程,请检查您在数据库中使用的成分名称,这些名称应与
BuildControls.js
中的相同,成分类型应与您在数据库中编写的相同。这肯定会解决你的问题


出现此错误的原因是选择了错误的名称,这就是为什么会显示无效的数组长度。

感谢大家花时间提供答案和想法。 我也有同样的问题,解决方法就是将键值改为小写

例如,下面的代码: 错误是将
'Price'
大写,而不是
'Price'
小写

checkoutContinuedHandler=()=>{
常量queryParams=[];
用于(让我们输入此。状态。成分){
queryParams.push(encodeURIComponent(ing)+'='+encodeURIComponent(this.state.components[ing]);
}
queryParams.push('price='+this.state.totalPrice.toFixed(2));
const queryString=queryParams.join('&');
这个。道具。历史。推({
路径名:'/checkout',
搜索:“?”+查询字符串
});

}
我走的是同样的道路,面临同样的问题。将
totalPrice
作为键值对包含在配料对象(在reducer.js文件中)中,但情况并非如此,因为它是每个操作处于更新状态的单独键值对

修理前-

import * as actionTypes from './actions';

const initialState = {
    ingredients: {
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0
    },
    totalPrice: 4,
};

const INGREDIENT_PRICES = {
    salad: 0.5,
    bacon: 1.3,
    cheese: 0.6,
    meat: 1,
};

const reducer = (state = initialState, action) => {
    switch(action.type){
        case actionTypes.ADD_INGREDIENT: return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] + 1,
                `totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]`
            }
        };

        case actionTypes.REMOVE_INGREDIENT: return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] - 1,
                `totalPrice: state.totalPrice - INGREDIENT_PRICES[action.ingredientName]`
            }
        }

        default : return state;
    }
};

export default reducer;
修理后-

import * as actionTypes from './actions';

const initialState = {
    ingredients: {
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0
    },
    totalPrice: 4,
};

const INGREDIENT_PRICES = {
    salad: 0.5,
    bacon: 1.3,
    cheese: 0.6,
    meat: 1,
};

const reducer = (state = initialState, action) => {
    switch(action.type){
        case actionTypes.ADD_INGREDIENT: return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] + 1,
            },
            `totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]`
        };

        case actionTypes.REMOVE_INGREDIENT: return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] - 1,
            },
            `totalPrice: state.totalPrice - INGREDIENT_PRICES[action.ingredientName]`
        }

        default : return state;
    }
};

export default reducer;

只需将spread操作符从…state.components中移除,它就会工作

事实上,我是一个新的反应,我正在遵循一个过程。复制代码后,错误消失了,但我的浏览器出现了另一个错误:
超出了最大更新深度。当组件在componentWillUpdate或componentDidUpdate内重复调用setState时,可能会发生这种情况。React限制嵌套更新的数量以防止无限循环。
对此有任何解决方案吗?是否在渲染方法中的某个位置调用
setState
?不,我没有。你可以查看我的完整代码,从屏幕截图上看,错误似乎来自
Ingredithandler
方法,但我在你的代码中找不到它。我的任何成分都不会有负值。问题所涉及的错误已解决,但我现在遇到另一个错误(检查第一个答案中的注释)
import * as actionTypes from './actions';

const initialState = {
    ingredients: {
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0
    },
    totalPrice: 4,
};

const INGREDIENT_PRICES = {
    salad: 0.5,
    bacon: 1.3,
    cheese: 0.6,
    meat: 1,
};

const reducer = (state = initialState, action) => {
    switch(action.type){
        case actionTypes.ADD_INGREDIENT: return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] + 1,
                `totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]`
            }
        };

        case actionTypes.REMOVE_INGREDIENT: return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] - 1,
                `totalPrice: state.totalPrice - INGREDIENT_PRICES[action.ingredientName]`
            }
        }

        default : return state;
    }
};

export default reducer;
import * as actionTypes from './actions';

const initialState = {
    ingredients: {
        salad: 0,
        bacon: 0,
        cheese: 0,
        meat: 0
    },
    totalPrice: 4,
};

const INGREDIENT_PRICES = {
    salad: 0.5,
    bacon: 1.3,
    cheese: 0.6,
    meat: 1,
};

const reducer = (state = initialState, action) => {
    switch(action.type){
        case actionTypes.ADD_INGREDIENT: return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] + 1,
            },
            `totalPrice: state.totalPrice + INGREDIENT_PRICES[action.ingredientName]`
        };

        case actionTypes.REMOVE_INGREDIENT: return {
            ...state,
            ingredients: {
                ...state.ingredients,
                [action.ingredientName]: state.ingredients[action.ingredientName] - 1,
            },
            `totalPrice: state.totalPrice - INGREDIENT_PRICES[action.ingredientName]`
        }

        default : return state;
    }
};

export default reducer;