我设计了一个React组件,该组件以块格式显示Pet Store的待办事项列表,以便用户可以按类别块组织待办事项,而不仅仅是未组织的待办事项列表。您可以在块列表的开头,中间或结尾的任意位置添加一个块,并且在后端可以正常使用,但是,在测试添加功能时,而不是在选定的位置添加块时,我的表始终如一将它们添加到表的底部即使在组件状态下顺序正确。
这是组件代码:
import React, { useEffect, useContext, Fragment } from 'react';
import ManagerContext from '../../../context/manager/managerContext';
import M from 'materialize-css';
import Todo from './Todo';
const Open = () => {
const managerContext = useContext(ManagerContext);
const {
openBlocks,
openTodos,
addNewBlock,
} = managerContext;
useEffect(() => {
M.AutoInit();
// eslint-disable-next-line
}, [openBlocks]);
return (
<div>
<h2>Opening Tasks</h2>
<table>
<tbody>
{openBlocks !== null &&
openBlocks.map((block) => (
<Fragment key={block.blockNum}>
<tr>
<td className="filler">
<button
className="btn btn-primary btn-block"
onClick={() => {
addNewBlock('Open', block.blockNum, openBlocks);
}}
>
{block.blockNum === 1
? `Add new block above Block #${block.blockNum}`
: `Add new block between Block #${
block.blockNum - 1
} & Block #${block.blockNum}`}
</button>
</td>
<td className="filler" colSpan="2"></td>
</tr>
<tr>
<td className="block-filler text-center">
<b>Block #{block.blockNum}</b>
</td>
<td className="block-filler text-center" colSpan="2">
<button className="btn btn-danger">Remove Block</button>
</td>
</tr>
<tr>
<th>Description</th>
<th>Category</th>
<th></th>
</tr>
{openBlocks.map((b) =>
b.todos.map(
(todo) =>
todo.block === block.blockNum && (
<Todo key={todo.id} todo={todo} />
)
)
)}
<tr>
<td className="filler">
<select name="addToBlock" id="addToBlock" defaultValue="">
<option value="" disabled>
Assign To-Do to Block #{block.blockNum}
</option>
{openTodos !== null &&
openTodos.map(
(t) =>
t.block === 0 && (
<option key={t.id} value={t.id}>
{t.todo} ({t.category} Task)
</option>
)
)}
</select>
</td>
<td className="filler" colSpan="2"></td>
</tr>
{block.blockNum === openBlocks.length && (
<tr>
<td className="filler">
<button className="btn btn-primary btn-block">
Add new block below Block #{block.blockNum}
</button>
</td>
<td className="filler" colSpan="2"></td>
</tr>
)}
</Fragment>
))}
</tbody>
</table>
</div>
);
};
export default Open;
从后端加载数据后,这里是openBlocks
的状态:
[
{blockNum: 1, todos: Array(1)}
{blockNum: 2, todos: Array(4)}
{blockNum: 3, todos: Array(2)}
{blockNum: 4, todos: Array(1)}
{blockNum: 5, todos: Array(2)}
{blockNum: 6, todos: Array(6)}
{blockNum: 7, todos: Array(1)}
]
这是浏览器中的组件:
如您所见,它将openBlocks
的内容加载到顺序编号的块中。
使用“在第1块上方添加新块”按钮时,它会以正确的开头状态显示:
[
{blockNum: 1, todos: Array(0)}
{blockNum: 2, todos: Array(1)}
{blockNum: 3, todos: Array(4)}
{blockNum: 4, todos: Array(2)}
{blockNum: 5, todos: Array(1)}
{blockNum: 6, todos: Array(2)}
{blockNum: 7, todos: Array(6)}
{blockNum: 8, todos: Array(1)}
]
但是,该组件会在结束处加载新块。
我觉得问题出在html表的呈现方式上,因此尝试将新数据添加到已建立的表中需要操作DOM。我不确定如何进行。任何帮助将不胜感激。