React中遇到未定义的props的问题
P粉949267121
P粉949267121 2023-09-08 21:45:04
0
1
567

我在 React 中编写了一个待办事项应用程序。我为多个部分创建组件。现在,每次我尝试运行该应用程序时,它都不会显示。

我总是收到错误 Uncaught TypeError: todo is undefined in footer.js:15。

我创建了一个待办事项列表应用程序,并将所有待办事项放入一个数组中,其中有使用状态待办事项。这是我在文件页脚中的组件 Todocounter 中传递的属性。

我尝试重命名该道具并更改其在页脚中的位置,以便在正确的位置调用。

这是app.js:

import React, { useState } from 'react';
import './App.css';
import InputTodos from './input.js';
import ListTodos from './list.js';
import TodoCounter from './footer.js';
import ClearButton from './clearbutton.js';

function App() {
  // create usestates for todos
  const [todo, setTodo] = useState([]);

  // render all components i have in diffrent files
  return (
    <div className="App">
      <div className="container">
        <div className="header">
          <InputTodos todo={todo} setTodo={setTodo} />
        </div>
        <div className="containerMid">
          <ListTodos todo={todo} />
        </div>
        <div className="footer">
          <TodoCounter todo={todo} />
        </div>
        <div className="buttonCleardiv">
          <ClearButton todo={todo} setTodo={setTodo} />
        </div>
      </div>
    </div>
  );
}

export default App;

这是 footer.js:

import React, { useEffect, useState } from 'react';

import './App.css';

// use effect to show whenever the array will change from completed todos to not completed
function TodoCounter(props) {
  const { todo } = props;
  const [completed, setCompleted] = useState(0);
  const [notCompleted, setNotCompleted] = useState(0);

  // filter between completed todos and not completed todos with cheackking the bolean status
  function counttodos(props) {
    const { todo } = props;
    return {
      completed: todo.filter((todo) => todo.isChecked).length,
      notCompleted: todo.filter((todo) => !todo.isChecked).length,
    };
  }
  //with the useeffect hook set the todos on completed or not completed if sth changes on the todos
  useEffect(() => {
    const { completed, notcompleted } = counttodos(todo);
    setCompleted(completed);
    setNotCompleted(notcompleted);
  }, [todo]);

  return (
    <div>
      <p>Completed: {completed}</p>
      <p>Not Completed: {notCompleted}</p>
      <p>Todos: {todo.length} </p>
    </div>
  );
}

export default TodoCounter;

P粉949267121
P粉949267121

全部回复(1)
P粉023326773

counttodos函数从组件中移出,这样它就不会在渲染时重新创建。因为你将todos作为参数传递给该函数,并且它没有被包装在另一个对象中,所以你可以直接使用它而不需要解构:

// 用布尔状态检查已完成和未完成的待办事项进行过滤
function counttodos(todos) {
  return {
    completed: todos.filter(todo => todo.isChecked).length,
    notCompleted: todos.filter(todo => !todo.isChecked).length,
  };
}

在组件本身中调用counttodos,并直接使用计算出的值而不将其存储为状态(参见@HenryWoody的评论):

function TodoCounter({ todo }) {
  // 使用useEffect钩子在todos发生变化时设置已完成或未完成的todos
  const { completed, notcompleted } = counttodos(todo);
  
  return (
    <div>
      <p>已完成:{completed}</p>
      <p>未完成:{notCompleted}</p>
      <p>待办事项:{todo.length} </p>
    </div>
  );
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板