将滤镜应用于ajax数据
问题描述:
我使用Redux从我的后端获取数据。将滤镜应用于ajax数据
componentWillMount() {
this.props.dispatch(fetchPlaces())
}
和我的行动:
export function fetchPlaces() {
return function(dispatch) {
dispatch({type: "FETCH_PLACES"});
let path = "/server/places"
axios.get(path)
.then((response) => {
dispatch({type: "FETCH_PLACES_FULFILLED", payload: response.data})
})
.catch((err) => {
dispatch({type: "FETCH_PLACES_REJECTED", payload: err})
})
}
}
和我的减速器:我使用取从我的智能组件的数据
const reducer = (state={
places: [],
isFetching: false,
error: null
}, action) => {
switch(action.type) {
case "FETCH_PLACES" : {
return { ...state, isFetching: true }
}
case "FETCH_PLACES_REJECTED" : {
return { ...state, isFetching: false, error: action.payload }
}
case "FETCH_PLACES_FULFILLED" : {
return { ...state, isFetching: false, places: action.payload }
}
default:
return state
}
}
每个地方都有一个属性叫做good_for
,这是一个字符串数组。
我现在希望能够通过标记过滤地点(通过已经存在的查询字符串传递),但是我需要能够在从数据库中检索地点后直接进行此操作。
我该如何在“Redux方式”中进行整合?
答
你在你的问题中提到
我需要能够从数据库中
已检索到的地方后,直做到这一点。如果这意味着data
已经在client
侧你已经提取了AFTER
,那么你可以使用Array.filter()
方法来做到这一点。像这样:
// For example your "good_for" field contains the following
const good_for = [ 'place1', 'place2', 'place3' ];
good_for.filter(p => p === 'place2');
希望这有助于^^,
答
在Ajax请求(axios.get
)后的承诺then
,可以先派遣到减速前过滤。
假设从查询字符串的地方候选人被称为goodPlaces
和array of string
前的形式:var goodPlaces = ["germany","japan","russia"]
和我们使用var lo = require('lodash')
。
.then((response) => {
var places = response.data;
var filtered = lo.filter(places, p=> goodPlaces.indexOf(p) > -1);
dispatch({type: "FETCH_PLACES_FULFILLED", payload: filtered})
})
当然,您使用的过滤逻辑和工具是灵活的。你只需要在调度之前做到这一点。