javascript - 类型错误 : Cannot read property 'length' of undefined react

标签 javascript reactjs undefined create-react-app

我正在 React 中做一个简单的练习。练习的目标很简单:

  • 从数组中随机抽取水果
  • 记录消息“请给我一个随机水果。”
  • 记录消息“给你:随机水果”
  • 记录消息“美味!我可以再来一份吗?”
  • 从水果数组中移除水果
  • 记录消息“抱歉,我们都出去了。我们还剩 FRUITSLEFT。

运行此代码时,我遇到了以下错误。由于某种原因,“长度”似乎是问题所在。

TypeError: Cannot read property 'length' of undefined
Module../src/index.js
C:/Users/jaina/Desktop/ReactAPPS/exercise1/exercise-one/src/index.js:15
  12 | // Remove the fruit from the array of fruits
  13 | let remaining = remove(foods, fruit);
  14 | // Log the message “I’m sorry, we’re all out. We have FRUITSLEFT left.”
> 15 | console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);
  16 | 

它还显示 __webpack_require__ 以及其他 webpack 警告。但我假设不运行的主要原因是“长度”未定义。

index.js

import foods from './foods';
import { choice, remove } from './helpers';

// Randomly draw a fruit from the array
let fruit = choice(foods);
// Log the message “I’d like one RANDOMFRUIT, please.”
console.log(`I’d like one ${fruit}, please.`);
// Log the message “Here you go: RANDOMFRUIT”
console.log(`Here you go: ${fruit}`);
// Log the message “Delicious! May I have another?”
console.log('Delicious! May I have another?');
// Remove the fruit from the array of fruits
let remaining = remove(foods, fruit);
// Log the message “I’m sorry, we’re all out. We have FRUITSLEFT left.”
console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);

Foods.js

const foods = [
    "🍇", "🍈", "🍉", "🍊", "🍋", "🍌", "🍍", "🍎",
    "🍏", "🍐", "🍒", "🍓", "🥝", "🍅", "🥑",
];

export default foods;

helper.js

function choice(items){
    let idx = Math.floor(Math.random()* items.length);
}

function remove(items, item){
    for (let i = 0; i < items.length; i++){
        if(items[i] === item){
            return [ ...items.slice(0,i), ...items.slice(i+1)];
        }
    }
}

export {choice, remove};

感谢任何帮助。

最佳答案

helper.js 中,如果您的函数 remove 没有找到任何内容,它将返回 undefined。然后,当你说...

console.log(`I’m sorry, we’re all out. We have ${remaining.length} other foods left.`);

...您假设 remaining 是一个数组,但它实际上是未定义的。

尝试将 return items; 放在 remove 函数末尾、for 循环之后。

关于javascript - 类型错误 : Cannot read property 'length' of undefined react,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61217450/

相关文章:

javascript - 如何使 Javascript 代码分别为每个元素工作,以使用相同的 Javascript 代码在 HTML 中创建多个副本

C++ 标识符未定义

javascript - 推送后未定义的数组

javascript - next.js 环境变量未定义(Next.js 10.0.5)

javascript - 停止发送电子邮件

javascript - Coffeescript/Javascript 为什么,克隆数组中的对象在传递给方法时似乎丢失了它们的引用?

javascript - ASP.NET Ajax 不调用 Url

reactjs - 当 prop 数据更改时,React 组件不会刷新

json - 将 GeoJSON 文件导入 React-Leaflet

javascript - ReactJS 高阶组件不在渲染循环中转发属性