客户端使用useReducer进行过滤

问题描述 投票:0回答:1

我有一个交易表,其中包含一些数据。我正在尝试使客户端过滤器更改搜索输入。

它首先工作,到下一个onChange事件,它过滤先前过滤的数据而不是初始数据。

我怎样才能使它始终在每个onChange事件上过滤初始状态?

如果有更好的方法,请告诉我

//Table
const [transactions, setTransactions] = useReducer(
    transactionsReducer,
    fetchTransactions()
  )
//Reducer
const transactionsReducer = (state, action) => {
  switch (action.type) {
    case 'filter':
      return action.transactions.filter(item =>
        item.description.includes(action.searchTerm)
      )

    default:
      return state
  }
}
//Search component (it receives setTransactions function as a prop)
const Search = ({ setTransactions }) => {
  const handleChange = event => {
    setTransactions({
      type: 'filter',
      searchTerm: event.target.value
    })
  }

  return (
    <form>
      <Input
        type="text"
        name="search"
        placeholder="search"
        onChange={handleChange}
      />
    </form>
  )
}
reactjs filter react-hooks
1个回答
0
投票

我像这样从fetchTransactions()将事务传递给Search组件

<Search
  setTransactions={setTransactions}
  transactions={fetchTransactions()}
/>

然后将此事务作为操作传递给我的reducer:

const handleChange = event => {
   setTransactions({
     type: 'filter',
     transactions, //like this
     searchTerm: event.target.value
   })
}

并在我的reducer中过滤此事务:

const transactionsReducer = (state, action) => {
  switch (action.type) {
    case 'filter':
      return action.transactions.filter(item =>
        item.description.includes(action.searchTerm)
      )

    default:
      return state
  }
}

它工作正常。如果有更好的方法,请告诉我

© www.soinside.com 2019 - 2024. All rights reserved.