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

3
我不理解为什么这段代码无法运行。它可以从状态中的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测试它。
1个回答

3
你需要对新列表进行解构:setPeople([...aux]); 否则 React 将认为没有任何更改。

你说得对!现在你这么一说,我完全记得以前也发生过同样的事情。谢谢。 - akirasephyr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接