【问题标题】:Component Exception (undefined is not an object (evaluating 'list.todos.filter')组件异常(未定义不是对象(评估'list.todos.filter')
【发布时间】:2021-06-22 19:39:32
【问题描述】:

我正在开发我的第一个 React 应用程序 - 一切都很顺利,但突然间我开始收到上面提到的错误。我不知道对我的代码进行任何更改,因此对于我作为一个绝对的初学者来说,很难发现错误。我已经尝试修复代码两天了,正在考虑重新开始。我所知道的是过滤器似乎是问题,但我真的看不出它有什么问题。我试图寻找答案,但没有找到真正帮助我解决问题的方法。

错误

这是我的代码:

import React from "react";
import { StyleSheet, Text, View, TouchableOpacity, Modal } from "react-native";
import colors from "../colors";
import TodoModal from "./TodoModal";

export default class TaskList extends React.Component {
  state = {
    showListVisible: false,
  };

  toggleListModal() {
    this.setState({ showListVisible: !this.state.showListVisible });
  }
  render() {
    const list = this.props.list;

    const completedCount = list.todos.filter(todo => todo.completed).length;
    const remainingCount = list.todos.length - completedCount;

【问题讨论】:

  • 错误告诉您this.props.list 未定义。您可能需要处理 TaskList 中未定义的情况,或检查父组件获取此 list 对象的逻辑是否正确,并且在未定义时正确处理

标签: react-native components expo undefined


【解决方案1】:

我的猜测是在初始渲染期间,this.props.listnull。您所要做的就是编写一行代码来防止这种情况发生。

  render() {
    const list = this.props.list;

    if (!list) return null; // or return some sort of loading element

    const completedCount = list.todos.filter(todo => todo.completed).length;
    const remainingCount = list.todos.length - completedCount;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2016-12-04
    • 2019-09-26
    • 2019-12-12
    • 2019-08-16
    • 2017-01-16
    • 2020-08-06
    相关资源
    最近更新 更多