[英]How to find/filter state from 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
});
我的猜測是categoryId
是一個字符串,您正在使用嚴格相等===
進行比較。 嘗試state.categories.find((item) => item.id === Number(categoryId))
。 希望能有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.