首页 > 解决方案 > Redux Action Dispatches 但不映射到状态

问题描述

我有一个我试图在我的组件中使用的动作,我的 FetchPosts() 函数将工作并映射到状态,但是当我使用我的其他动作 FetchUserPosts() 时,我可以在动作调度的 redux 开发工具中看到,但是在状态中什么都没有,状态根本没有改变。

这可能与我的行为有关,但我不确定。

postAction.js

import { FETCH_POSTS, NEW_POSTS, FETCH_POST_FOR_APPROVAL, 
FETCH_POSTS_FROM_USER  } from './types';

export const fetchPostsFromUser = (id) => dispatch => {
Promise.all([fetch('http://10.6.254.22:5000/posts/1' + id)])
.then(([res1]) => { 
 return Promise.all([res1.json()]) 
})
.then(([posts]) => dispatch ({
  type: FETCH_POSTS_FROM_USER,
  payload: posts
 }));
}

类型.js

 export const FETCH_POSTS_FROM_USER = 'FETCH_POSTS_FROM_USER';

PostReducer.js

import { FETCH_POSTS, NEW_POSTS, FETCH_POST_FOR_APPROVAL, 
FETCH_POSTS_FROM_USER } from '../actions/types';

const initialState = {
items: [],
item: {}
}

export default function (state = initialState, action ){
switch(action.type) {
    case FETCH_POSTS:
        console.log('currently reducing')
    return{
        ...state, 
        items: action.payload
    } 
    case NEW_POSTS:
        return{
            ...state,
            item: action.payload
        }
    case FETCH_POST_FOR_APPROVAL:
        return{
            ...state,
            items: action.payload
        }
    case FETCH_POSTS_FROM_USER:
        return{
            ...state,
            items: action.payload
        }
    default:
        return state;
  }
}

我的组件我希望该功能可以使用,以便我可以映射道具。

class ProfilePostBody extends Component {

 constructor(props){
 super(props)
 this.state = {
  commentBody: null,
  postId: null,
  giphyUrl: null,
  postPicture: null,
  userId: null,
  userIdto: null,
  userIdName: null,
  userIdtoName:null,
  // postBody: null,
  // giphyUrl: null,
  // userIdto: null,
  // userIdName: null,
  // userIdtoName:'Julio',

  displayGifPicker: false
 }
 }

componentDidMount(){
  this.props.fetchPostsFromUser();
  this.props.fetchPosts();

}



render () {
 return (
  // <Grid item xl={6}>
  <div>
    {this.props.posts.map((post, index) =>
      <PostBodyTemplate key={index} postId={post.id}  onSubmit= 
{this.handleSubmit} onChange={e => 
this.handleInputChange(e,post.id,post.userId,post.userIdName)} title= 
{post.title} postBody={post.postBody} 
           giphyUrl = {post.giphyUrl} userWhoPosted={post.userIdName} 
commentBody={post.commentBody} userIdtoName={post.userIdtoName} 
 userIdName={post.userIdName} />
       )} 
</div>
 )
}

}

ProfilePostBody.propTypes = {
fetchPostsFromUser: PropTypes.func.isRequired,
fetchPosts: PropTypes.func.isRequired,
posts: PropTypes.array.isRequired
}

const mapStateToProps = state =>({
posts: state.posts.items
})

export default connect(mapStateToProps, { fetchPosts, fetchPostsFromUser 
}) 
 (ProfilePostBody);

fetchPosts 会起作用,但如果我将其注释掉并尝试 fetchPostsFromUser() 它将不起作用。

标签: javascriptreactjsredux

解决方案


推荐阅读