【发布时间】:2018-04-16 20:02:59
【问题描述】:
我正在渲染数据(将它放在我的 redux 存储中),我有一个搜索栏,并希望根据搜索输入过滤数据结果。我正在使用重新选择库,但似乎无法使其工作。我阅读了他们的文档并尝试了各种方法:
我将搜索输入存储在本地状态并希望将其作为参数传递,但它似乎只适用于我没有的道具(因为我将输入保存在 comp 状态。) 然后我尝试在我的 onChange 函数中调用我的选择器函数,传入输入 --> 这里的问题是,我接收到输入,但没有接收到数据。
有人可以帮忙吗?
selector.js
import {createSelector} from 'reselect'
const dataSelector = (state, props) => {
return state.data;
}
export const filterResults = (data, input) => {
return createSelector(
dataSelector,
data => data.filter((item) => item.symbol.toLowerCase().includes(input) || item.name.toLowerCase().includes(input))
)
}
容器:
class App extends React.Component {
constructor(props){
super(props);
this.state = {
searchInput: ""
}
}
filterData = (e)=> {
const input = e:
this.setState({
searchInput:input
})
}
render (){
...
this.props.products.data.map((item, index) =>...
...
<input
onChange={this.filterData}
/>
}
}
function mapStateToProps(state, props) {
return {
products: state.data,
filteredData: filterResults(state,this.state.input)
}
}
export default connect(mapStateToProps, { actioncreator })(App)
更新:
我更改了代码,现在将输入存储在我的 redux 存储中。我在我的 onChange 函数中调用我的 actioncreator,它返回(仅)输入,我的(输入)reducer 也在我的 mapstatetoprops 函数中返回。
选择器:
import {createSelector} from 'reselect'
const selectedData = state => state.data;
const input = state => state.searchFilter.searchInput;
const getData = (data, searchInput) => {
return data.filter((item) => item.name.toLowerCase().includes(searchInput))
}
export default createSelector(
selectedData,
input,
getData
)
在我的容器中,我将 mapStateToProps 更改为:
从...导入选定数据
function mapStateToProps(state) {
return {
products: state.data,
searchFilter: state.searchFilter,
selected: selectedData(state)
}
}
问题:
我收到错误:无法过滤 null - 但是当我在 getData 函数中控制台日志数据时 - 我确实得到了一个充满对象的数组,因此它不为 null
1234563
【问题讨论】: