TypeError 无法读取未定义的属性“查找”

时间:2021-02-09 05:50:22

标签: reactjs react-redux

我正在创建一个 react-redux 待办事项应用程序,在 UI 中单击视图时出现此错误。我正在尝试查看每个待办事项,但收到此错误,我已尝试多次摆脱此错误,但仍然收到此错误。

import React from "react";
import { useSelector } from "react-redux";

export const SingleTodoPage = ({ match }) => {
  const { todoId } = match.params;

  const todo = useSelector((state) => {
    state.todos.find((todo) => todo.id === todoId);
  });

  return (
    <div>
      <h2>{todo.name}</h2>
      <p>{todo.description}</p>
    </div>
  );
};

enter image description here

这里是 codesandbox 链接

1 个答案:

答案 0 :(得分:1)

问题

在配置商店时,您将 TodoReducer 减速器添加为 todo,而不是 todos

export default configureStore({
  reducer: {
    todo: TodoReducer
  }
});

在选择器中引用 state.todos:

const todo = useSelector((state) => {
  state.todos.find((todo) => todo.id === todoId);
});

第二个问题是您的选择器还需要返回一个值。

解决方案

通过执行以下操作之一正确/一致地引用状态。

  1. 更新 reducer 名称以匹配选择器中的用法

    export default configureStore({
      reducer: {
        todos: TodoReducer
      }
    });
    
  2. 更新您的选择器用法以匹配根减速器

    const todo = useSelector((state) => {
      state.todo.find((todo) => todo.id === todoId);
    });
    

修复选择器也返回一个值。

const todo = useSelector((state) => {
  return state.todo.find((todo) => todo.id === todoId);
});

如果没有找到匹配项,array.prototype.find 也会返回 undefined,因此您的 UI 应该处理这个问题。如果未找到 todo,则有条件地呈现匹配的结果或 null。

export const SingleTodoPage = ({ match }) => {
  const { todoId } = match.params;

  const todo = useSelector((state) => {
    return state.todo.find((todo) => todo.id === todoId);
  });

  return todoId ? (
    <div>
      <h2>{todo.name}</h2>
      <p>{todo.description}</p>
    </div>
  ) : null;
};

Edit typeerror-cannot-read-property-find-of-undefined