Redux没有更新initialState

时间:2019-04-13 18:35:03

标签: reactjs redux react-redux

我正在从自己的操作中检索帖子,并且帖子未显示在

console.log(this.props.posts)

无论如何,它确实会显示在console.log动作下

相反,我明白了

enter image description here

理想情况是在posts:Array中显示 Array(2)。因此看来redux不会更新initialState posts数组,因此无法检索帖子。将action.data.data更改为action.data不会有任何改变。

actions.js

export const GetPosts = () => {
    return (dispatch, getState) => {
        return Axios.get('/api/posts/myPosts')
            .then( (res) => {
                 const data = {
                     data: res.data
                 }
                 console.log(data); // logs data and i can see an array 
                 dispatch({type: GET_POSTS, data })
             })

    }
}

因此,我更新了状态,以便能够在组件中检索它。

posts.js

import { POST_FAIL, GET_POSTS, POST_SUCC, DELETE_POST} from '../actions/';

const initialState = {
    post: [],
    postError: null,
    posts:[]
}

export default (state = initialState, action) => {
    switch (action.type) {
        case POST_SUCC:
            return ({
                ...state,
                post:action.post
            });

        case POST_FAIL:
            return({
                ...state,
                postError: action.err.response.data
            })
        case GET_POSTS:
            // console.log(action.data.data)
            return {...state, posts: action.data.data}
        // case DELETE_POST:
        //     return ({
        //         ...state,
        //        posts: action.posts.filter(post => post.id !== action.posts[0].id)
        //     })
        default:
            return state
    }
}

Posts.js

import React, { Component } from 'react';
import PostList from './PostList';
import Axios from '../Axios';
import {connect} from 'react-redux';
import { withRouter, Redirect} from 'react-router-dom';
import {DeletePost, GetPosts} from '../actions/';

const Styles = {
    myPaper:{
      margin: '20px 0px',
      padding:'20px'
    }
    , 
    wrapper:{
      padding:'0px 60px'
    }
}
class Posts extends Component {
    state = {
      posts: [],
      loading: true,
    }

  componentWillMount(){
    this.props.GetPosts();
    // renders an empty posts array
    console.log(this.props.posts);
  }

  onDelete = (id) => {
    Axios.post(`/api/posts/delete/${id}`);
    this.setState({
      posts: this.state.posts.filter(post => post.id !== id)
    })
  }


  render() {
    const {loading, posts} = this.state;
    if (!this.props.isAuthenticated) {
      return (<Redirect to='/signIn' />);
    }
    if(loading){
      return "loading..."
    }
    return (
      <div className="App" style={Styles.wrapper}>
        <h1> Posts </h1>
        {/* <PostList posts={this.props.posts}/> */}
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  isAuthenticated: state.user.isAuthenticated,
  // i know i have to use state.post.posts but i wanted to get an idea if the 
  // initialize state updated at all
  posts: state.post
})
const mapDispatchToProps = (dispatch, state) => ({
  // newPost: (post) => dispatch(newPost(post)),
  // DeletePost: (id) => dispatch( DeletePost(id))
  GetPosts: () => dispatch( GetPosts())
});
export default withRouter(connect(mapStateToProps,mapDispatchToProps)(Posts));

1 个答案:

答案 0 :(得分:1)

您的reducer正在设置posts状态属性:

case GET_POSTS:
            // console.log(action.data.data)
            return {...state, posts: action.data.data}

您的组件正在将post状态属性映射到组件的posts属性:

const mapStateToProps = (state) => ({
  isAuthenticated: state.user.isAuthenticated,
  // i know i have to use state.post.posts but i wanted to get an idea if the 
  // initialize state updated at all
  posts: state.post
})