我正在使用Redux从后端获取数据。我使用以下方法从智能组件中获取数据:
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
已经位于您获取AFTER
client
端,那么您可以使用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
之后的 promise then
上,你可以先过滤它,然后再调度到 reducer。
假设查询字符串中的候选位置被称为 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})
})
当然,您使用的过滤逻辑和工具是灵活的。您只需要在调度之前完成即可。