【问题标题】:React - Removing item from array not rerendering listReact - 从数组中删除项目而不是重新渲染列表
【发布时间】:2021-01-22 19:47:14
【问题描述】:

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

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

【问题讨论】:

    标签: javascript reactjs typescript rendering use-state


    【解决方案1】:

    你需要解构新列表:setPeople([...aux]); 否则 React 会认为没有任何改变。

    【讨论】:

    • 你是对的!既然你这么说了,我完全记得以前发生在我身上的同样的事情。谢谢。
    猜你喜欢
    • 2018-04-18
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 2022-07-23
    • 1970-01-01
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多