我对如何在React组件中访问Redux状态内的字段有疑问:
Reducer.js
import { fromJS } from 'immutable';
import { combineReducers } from 'redux';
import {
LOAD_HEADERS_SUCCESS,
LOAD_HEADERS_ERROR
} from '../constants';
const initialState = fromJS({
posts: []
});
const homeReducer = (state = initialState, action) => {
switch(action.type) {
case LOAD_HEADERS_SUCCESS:
return Object.assign({}, state, {
posts: action.payload
});
case LOAD_HEADERS_ERROR:
return state;
default:
return state;
}
};
const rootReducer = combineReducers({
homeReducer
});
export default rootReducer;
我使用redux-saga来处理extrnal API调用
Sagas.js
import { call, put, takeEvery, takeLatest, all } from 'redux-saga/effects';
import { fetchHeaders } from '../api';
import { loadHeaderSuccess, loadHeaderError } from '../actions';
import {
LOAD_HEADERS_REQUEST,
} from '../constants';
function* loadPostsHeader(action) {
try {
const response = yield call(fetchHeaders);
yield put(loadHeaderSuccess(response.data));
} catch (error) {
yield put(loadHeaderError(error));
}
}
function* headerSaga() {
yield takeLatest(LOAD_HEADERS_REQUEST, loadPostsHeader);
}
export default function* rootSaga() {
yield all([
headerSaga()
]);
}
HomePage.js
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import H2 from '../../components/H2';
import Section from './Section';
import PageBlock from '../../components/PageBlock';
import P from '../../components/P';
import { loadHeaderRequest } from '../../actions';
class HomePageContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function
componentDidMount() {
this.props.onHomeLoad();
}
render() {
const { posts } = this.props;
return (
<div>
<PageBlock>
<div>
<H2>
Latest Articles
</H2>
<P>
{ posts != undefined ? posts[0].title : 'ERR' }
</P>
</div>
</PageBlock>
</div>
);
}
}
HomePageContainer.PropTypes = {
posts: PropTypes.array,
onHomeLoad: PropTypes.func
};
const mapStateToProps = state => {
console.log(state.homeReducer.posts);
return { posts: state.homeReducer.posts };
};
const mapDispatchToProps = dispatch => {
return {
onHomeLoad: () => {
dispatch(loadHeaderRequest());
}
};
};
const HomePage = connect(mapStateToProps, mapDispatchToProps)(HomePageContainer);
export default HomePage;
问题出在 mapStateToProps :如果我使用 state.homeReducer.posts 一切正常,否则如果我尝试 state.posts ,帖子总是未定义。
我见过许多例子,其中直接访问该字段而中间没有减速器的名称。
我想知道为什么在我的代码中不是这种情况。
谢谢!
答案 0 :(得分:1)
我使用state.homeReducer.posts一切正常,否则如果我尝试state.posts,帖子总是未定义的。
你这样设置它。 homeReducer
是州树中的一个支行。您需要使用它才能访问它的数据。但以不同的方式称呼它会更好,例如:
const rootReducer = combineReducers({
home: homeReducer
});
然后你会使用state.home.posts
。
答案 1 :(得分:0)
如果你想在一个模块中使用所有reducer,你可以直接使用state.posts,因为你可以放下combineReducers
const rootReducer = homeReducer;
export default homeReducer;