我有一个交易表,其中包含一些数据。我试图使客户端过滤器onChange的搜索输入。
首先运行,直到下一个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>
)
}
答案 0 :(得分:0)
我这样将交易从fetchTransactions()传递到搜索组件
<Search
setTransactions={setTransactions}
transactions={fetchTransactions()}
/>
,然后将此交易作为操作传递给我的减速器:
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
}
}
,效果很好。如果有更好的方法,请告诉我