要按类别筛选React Redux,可以使用以下步骤和示例代码:
npx create-react-app my-app
cd my-app
npm install react-redux
// store.js
import { createStore } from 'redux';
const initialState = {
items: [
{ name: 'Item 1', category: 'Category 1' },
{ name: 'Item 2', category: 'Category 2' },
{ name: 'Item 3', category: 'Category 1' },
// ...
]
};
function reducer(state = initialState, action) {
// ...
}
const store = createStore(reducer);
export default store;
import React from 'react';
import { connect } from 'react-redux';
function ItemList(props) {
const { items, category } = props;
const filteredItems = items.filter(item => item.category === category);
return (
{category}
{filteredItems.map(item => (
- {item.name}
))}
);
}
function mapStateToProps(state) {
return {
items: state.items
};
}
export default connect(mapStateToProps)(ItemList);
ItemList
组件进行筛选和显示。import React from 'react';
import { Provider } from 'react-redux';
import store from './store';
import ItemList from './ItemList';
function App() {
const categories = ['Category 1', 'Category 2', 'Category 3'];
return (
{categories.map(category => (
))}
);
}
export default App;
这样,你就可以按类别筛选并显示React Redux中的数据了。在上面的示例中,我们通过Redux store来存储和管理数据,并在React组件中使用React Redux库来连接store并获取数据。然后,我们根据特定的类别筛选数据,并在组件中显示筛选后的数据。
下一篇:按类别筛选产品