在我的react hooks组件中,我正在从对象数组中渲染数据。
const lineInfo = [
{
id: '001',
line: 's-1125026',
arrival: '7:30',
departure: '8:00',
authorization: 'User 1',
},
{
id: '002',
line: 's-1125027',
arrival: '8:01',
departure: '8:50',
authorization: 'User 1',
},
在.map()
中,我使用以下数据返回数据:
<div>
{lineInfo.map((line) => (
<Row key={`line_${line.id}`}>
// remaining code removed for length
列表返回正常,所以现在我试图从列表中删除一行。 删除功能
const [list, setList] = useState(lineInfo);
function handleRemove(id) {
console.log('id' id);
const newList = list.filter((line) => line.id !== id);
setList(newList);
}
删除按钮
<Button
className={style.close_button}
onClick={() => handleRemove(line.id)}
>
<img src={close} alt="trash" />
</Button>
</Row>
我遇到的问题是在控制台日志中,是仅从数组中删除了line.id而不是整个数据行。
我对钩子不太熟悉,只能找到有关类组件的特定问题的示例。预先感谢。
答案 0 :(得分:2)
您应该显示带有挂钩的已定义状态。在这种情况下,list
而不是lineInfo
。
<div>
{list.map((line) => (
<Row key={`line_${line.id}`}>
// remaining code removed for length
答案 1 :(得分:1)
您不应渲染lineInfo,而应从本地状态渲染列表:
const { useState, useCallback } = React;
const lineInfo = [
{
id: '001',
line: 's-1125026',
arrival: '7:30',
departure: '8:00',
authorization: 'User 1',
},
{
id: '002',
line: 's-1125027',
arrival: '8:01',
departure: '8:50',
authorization: 'User 1',
},
];
//make row pure component using React.memo
const Row = React.memo(function Row({ item, remove }) {
return (
<div>
<pre>{JSON.stringify(item, undefined, 2)}</pre>
<button onClick={() => remove(item.id)}>
remove
</button>
</div>
);
});
const App = () => {
const [list, setList] = useState(lineInfo);
//make remove a callback that is only created
// on App mount using useCallback with no dependencies
const remove = useCallback(
(removeId) =>
//pass callback to setList so list is not a dependency
// of this callback
setList((list) =>
list.filter(({ id }) => id !== removeId)
),
[]
);
return (
<ul>
{list.map((line) => (
<Row
key={`line_${line.id}`}
item={line}
remove={remove}
/>
))}
</ul>
);
};
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>