我是本机和redux的新手。当我将组件连接到商店并使用mapStateToProps函数将状态映射到组件prop时,我注意到组件状态位于state.component_reducer,例如,如果我在组件中存储了一个名为isFetching的变量,则我可以在state.isFetching中达到它(正如我在react redux文档中阅读的那样),但就我而言,我可以在state.component_reducer.isFetching中达到它。 我想我做错了什么,但我不知道这是什么。
actions.js
import OrdersAPI from '../../services/api/Orders'
export const REQUEST_ORDERS = 'REQUEST_ORDERS'
export const RECEIVE_ORDERS = 'RECEIVE_ORDERS'
export const requestOrders = username => ({
type: REQUEST_ORDERS,
})
export const receiveOrders = (json) => ({
type: RECEIVE_ORDERS,
orders: json
})
const fetchOrders = username => dispatch => {
dispatch(requestOrders(username))
return OrdersAPI.getUserOrders(username)
.then(json => dispatch(receiveOrders(json)))
}
// temp imp
const shouldFetchOrders = (state) => {
const orders = state.orders
if (!orders) {
return true
}
return false;
}
export const fetchOrdersIfNeeded = username => (dispatch, getState) => {
if (shouldFetchOrders(getState() == true)) {
return dispatch(fetchOrders(username))
}
}
组件化简器-reducer.js
import { REQUEST_ORDERS, RECEIVE_ORDERS } from './actions'
const INITIAL_STATE = {
orders: [],
}
function orders(state = INITIAL_STATE, action) {
switch(action.type) {
case REQUEST_ORDERS:
return Object.assign({}, state, {
...state,
})
case RECEIVE_ORDERS:
return Object.assign({}, state, {
...state,
orders: action.orders,
})
default:
return state
}
}
export default orders;
我的组件-OrdersList.js
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { connect } from 'react-redux'
import OrderCard from './OrderCard';
import { fetchOrdersIfNeeded } from './actions'
class OrdersList extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
const { dispatch } = this.props
dispatch(fetchOrdersIfNeeded("X"))
}
render() {
const { orders } = this.props;
const isEmpty = orders.length === 0
return (
isEmpty ?
<View>
<Text>Wishlist Empty!</Text>
</View>
:
this.props.orders.map((order) => (
<OrderCard key={order.OrderId.S} order={order} />
))
);
}
}
const mapStateToProps = (state) => {
const orders = state.ordersReducer.orders;
return {
orders
}
}
export default connect(mapStateToProps)(OrdersList);
store.js
import { createStore, applyMiddleware, combineReducers } from 'redux'
import thunk from 'redux-thunk'
import { createLogger } from 'redux-logger'
import wishlistReducer from '../components/WishlistGridList/reducer'
import ordersReducer from '../components/YourOrders/reducer'
const rootReducer = combineReducers({
wishlistReducer,
ordersReducer
})
const middleware = [ thunk ]
if (process.env.NODE_ENV !== 'production') {
middleware.push(createLogger())
}
const store = createStore(
rootReducer,
applyMiddleware(...middleware)
);
export default store;