我正在尝试熟悉react-boilerplate的流程。直到现在我都喜欢事物的简洁明了,虽然我觉得我错过了一块拼图。如果有更多经验的人可以帮助我,那就太好了。
我目前面临的问题如下。
- 我正在触发特定组件的 componentWillMount() 中的操作。
- 该操作正在创建
actions.js
,它是一个简单的获取请求axios
。 - 数据在 promise 中间件库中进行处理
redux-promise
。 - 承诺现在被传递到特定组件的减速器中,其中返回了整个状态和我需要的数据。
- 试图在组件上捕获这种状态是我失败的地方。我正在尝试 mapStateToProps 但无法找到我需要的数据,而是正在接收 Map {}。
如何用我的道具映射这个对象?
我确定我错过了一些重要的事情。
这是我的回购。 https://github.com/paschalidi/blog-react-redux
这是我的代码,因此您可以简要了解一下。
index.js
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { fetchPosts } from './actions'
import selectPostsIndex from './selectors'
export class PostsIndex extends React.Component { // eslint-disable-line react/prefer-stateless-function
componentWillMount() {
this.props.fetchPosts();
}
render() {
return (
<div>
<h3>Posts</h3>
<ul className="list-group">
A list would render here.
</ul>
</div>
);
}
}
function mapStateToProps(state) {
console.log(state.posts)
//return { posts: state } //****I dont get why the redux state is not being given here.
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchPosts }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(PostsIndex);
动作.js
import axios from 'axios'
import { FETCH_POSTS } from './constants';
const ROOT_URL = 'http://reduxblog.herokuapp.com/api';
const API_KEY = '?key=dsklhfksdhfjkdshfkjdshkj';
export function fetchPosts() {
const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
return {
type: FETCH_POSTS,
payload: request
};
}
store.js
import promise from 'redux-promise';
const middlewares = [
sagaMiddleware,
routerMiddleware(history),
promise
];
减速器.js
import { fromJS } from 'immutable';
import {
FETCH_POSTS
} from './constants';
const initialState = fromJS({ all:[], post: null });
function postsIndexReducer(state = initialState, action) {
switch (action.type) {
case FETCH_POSTS:
return { ...state, all: action.payload.data };
default:
return state;
}
}
export default postsIndexReducer;
该动作也在reducers.js中注册
import PostsReducer from 'containers/PostsIndex/reducer'
export default function createReducer(asyncReducers) {
return combineReducers({
route: routeReducer,
language: languageProviderReducer,
posts: PostsReducer,
form: reduxFormReducer,
...asyncReducers,
});
}