gpt4 book ai didi

javascript - React - 从数组中删除项目而不是重新渲染列表

转载 作者:行者123 更新时间:2023-12-05 03:48:44 27 4
gpt4 key购买 nike

我无法理解为什么这段代码不起作用。它从状态中的 people 数组中删除项目,但不会重新呈现列表。

import { render } from 'react-dom';
import axios from 'axios';
import ReactLoading from 'react-loading';
import useMediaQuery from '@material-ui/core/useMediaQuery';
import People from './components/People';
import './style.css';

interface PeopleData {
name: string;
eye_color: string;
}
interface PeopleResponse {
results: PersonagemData[];
}

const App: React.FC = () => {
const [loading, setLoading] = React.useState(true);
const [people, setPeople] = React.useState([]);
const isMobile = useMediaQuery('(max-width:768px)');

React.useEffect(() => {
axios.get<PeopleResponse>('https://swapi.dev/api/people/').then(response => {
setPeople(response.data.results);
setLoading(false);
console.log(response)
})
}, []);

const deleteChar = React.useCallback(index => {
let aux = people;
aux.splice(index, 1)
setPeople(aux);
}, [people])

return (
<div>
{loading ? (
<ReactLoading
type={'spin'}
color={'#800080'}
height={'10%'}
width={'10%'}
/>
):
people.map((element, index) =>
(<People
index={index}
name={element.name}
color={element.eye_color}
deleteChar={deleteChar}
/>))
}
</div>
);
}

render(<App />, document.getElementById('root'));

我不明白为什么它不重新渲染。我在 StackBlitz 上做这个,所以你可以在这个链接上测试它 https://react-ts-j1kkcp.stackblitz.io

最佳答案

您需要解构新列表:setPeople([...aux]); 否则 React 会认为什么都没有改变。

关于javascript - React - 从数组中删除项目而不是重新渲染列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64251064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com