【发布时间】:2017-04-20 23:55:18
【问题描述】:
我正在尝试熟悉react-boilerplate 的流程。 直到现在我都喜欢事物的简洁明了,虽然我觉得我错过了一块拼图。如果有更多经验的人可以帮助我,那就太好了。
我目前面临的问题如下。
- 我正在触发特定组件的 componentWillMount() 中的操作。
- 正在
actions.js中创建操作,它是使用axios发出的简单获取请求。 - 正在 Promise 中间件库
redux-promise中处理数据。 - promise 现在被传递到特定组件的 reducer 中,其中将返回整个状态和我需要的数据。
- 试图在组件上捕获此状态是我失败的地方。我正在尝试 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);
actions.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
];
reducer.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,
});
}
【问题讨论】:
标签: javascript reactjs promise redux react-boilerplate