reactjs 是否使用回调React删除someState[id]?

svujldwt  于 2023-03-01  发布在  React
关注(0)|答案(2)|浏览(101)

我可以在子组件?中更新父状态filters

const ParentComponent = () => {
  const [filters, setFilters] = useState()
  return (<></>)
}

const ChildrenComponent = ({ filters, setFilters }) => {
  const handleDelete = (id) => {
      const filtersCopy = { ...filters }
      delete filtersCopy[id]
      setFilters(filtersCopy)
  }
  return (<button onClick={() => handleDelete(1)}>Delete</button>)
}

有一些方法可以使用callback来获取prev状态,类似于:

setFilters(prev => { delete ...prev[id] }
5kgi1eie

5kgi1eie1#

您已经接近答案,因为可以访问prev状态:

const handleDelete = (id) => {
  setFilters(prevFilters => {
    const { [id]: deletedFilter, ...newFilters } = prevFilters;
    return newFilters;
  });
};
mnemlml8

mnemlml82#

在我看来,你的东西应该能起作用,所以也许你有另一个问题?

const ParentComponent = () => {
  const [filters, setFilters] = React.useState({ 1: 'Filter one', 2: 'Filter two' });
  
  return <ChildrenComponent filters={filters} setFilters={setFilters} />;
};

const ChildrenComponent = ({ filters, setFilters }) => {
  const handleDelete = (id) => {
    const filtersCopy = { ...filters };
    delete filtersCopy[id];
    setFilters(filtersCopy);
  };
  
  // with previous state and delete:
  // const handleDelete = (id) => {
  //   setFilters((previous) => {
  //     const filtersCopy = { ...previous };
  //     delete filtersCopy[id];
  //     return filtersCopy;
  //   });
  // };
  
  return <div>
    { Object.entries(filters).map( ([id, title]) => (
      <button key={id} onClick={() => handleDelete(id)}>Delete { title }</button>
    )) }
  </div>;
};

const App = () => {
  return <ParentComponent />;
};

ReactDOM.render(<App />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>

<div id="root"></div>

相关问题