反应不是通过redux数组映射

时间:2019-04-13 19:55:46

标签: reactjs redux

反应不是通过数组映射。我可以在控制台日志中看到这样的数组。显示正在加载而不是通过数组进行映射。

enter image description here

该数组来自redux reducer。我认为我根据redux正确地进行了所有操作。

reducer / posts.js

Base

是否可能是异步生命周期方法问题?

actions / index.js

import {GET_POSTS, '../actions/';

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

export default (state = initialState, action) => {
    switch (action.type) {
        case GET_POSTS:
            // console.log(action.data)
            return {...state, posts: action.data}
    default:
            return state

Posts.js

export const GetPosts = () => {
    return (dispatch, getState) => {
        return Axios.get('/api/posts/myPosts')
            .then( (res) => {
                 const data = [...res.data]

                 console.log(data); // logs data and i can see an array 

                 dispatch({type: GET_POSTS, data })
             })

    }
}

PostList.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 {


  constructor(props){
    super(props);

    this.state = {
      posts: [],
      loading: true,
    }
  }


  componentWillMount(){
    this.props.GetPosts();
    const reduxPosts = this.props.myPosts;
    const ourPosts = reduxPosts  
    console.log(reduxPosts); // shows posts line 35
  }

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


  render() {
    const {loading} = this.state;
    const { myPosts} = this.props
    if (!this.props.isAuthenticated) {
      return (<Redirect to='/signIn' />);
    }
    if(loading){
      return "loading..."
    }
    return (
      <div className="App" style={Styles.wrapper}>
        <h1> Posts </h1>
        {/* doesn't map posts instead shows loading */}
        <PostList posts={myPosts}/>
      </div>
    );
  }
}
const mapStateToProps = (state) => ({
  isAuthenticated: state.user.isAuthenticated,
  myPosts: state.post.posts
})
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)

在getPosts函数解析后,您的代码中似乎没有任何地方将loading设置为false-因此您的应用程序将始终返回“ loading ...”字符串。尝试这样的事情(假设GetPosts返回诺言):

  async componentWillMount(){
    await this.props.GetPosts();
    this.setState({ loading: false })
    const reduxPosts = this.props.myPosts;  
    console.log(reduxPosts); // shows posts line 35
  }