如何从React Redux查找/过滤状态

时间:2018-11-20 16:10:02

标签: reactjs redux react-redux

我正在尝试通过将参数传递给mapStateToProps来查找数据。

const mapStateToProps = (state, props) => {
const categoryId = props.match.params.id;
return {
    category: state.categories.find((item) => item.id === categoryId)
   };
};

export default connect(mapStateToProps)(categoryForm);

当我尝试(item.id === 1)时,获得类别的数据,但是当我尝试(item.id === categoryId)时,类别的数据未定义。我尝试控制台categoryId,可以从params获取ID,但是为什么当我这样尝试(item.id === categoryId)时它不起作用?

categoryAction.js

import api from '../api';
import { FETCH_CATEGORIES } from '../types';

export function setCategories(categories){
return {
    type: FETCH_CATEGORIES,
    categories
  }
}

export const fecthCategory = () => dispatch => 
    api.category.getCategories().then(categories => 
    dispatch(setCategories(categories)))

categoryReducer.js

import { FETCH_CATEGORIES } from '../types';

export default function categories(state = [], action ={}){
switch(action.type){
    case FETCH_CATEGORIES:
        return action.categories;
    default: return state;
  }
}

rootReducers.js

import { combineReducers } from 'redux';
import categories from './reducers/categoryReducer.js';

export default combineReducers({ 
     categories
});

1 个答案:

答案 0 :(得分:0)

我的猜测是categoryId是一个字符串,您正在使用严格相等的===进行比较。 尝试state.categories.find((item) => item.id === Number(categoryId))。 希望有帮助。