无法将价值从Redux获取到道具

时间:2018-07-05 11:07:15

标签: javascript reactjs redux

我无法从Redux获取props值,我检入了reducers,store和action JS文件,一切正常。甚至我都可以在下面的console.log("MAPSTOSTATEPROPS", state)函数内的mapsStateToProps中看到正确打印的状态。

但是当我给this.props.posts访问值时,我没有得到它们。不确定,我在哪里做错了。有人可以帮我吗?

posts.js:

class Posts extends Component {
  componentWillMount() {
    this.props.fetchPosts();
    **console.log(this.props.posts); // gives empty array result**
  }

  render() {
    return (
      <div>
        <h2>Posts</h2>
      </div>
    )
  }

  componentDidMount() {
    console.log("DID mount", this.props);
  }          
}

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

const mapsStateToprops = (state) =>  {
  **console.log("MAPSTOSTATEPROPS", state)** // gives correct result from current state
  return {
    posts: state.items
  }
};    

export default connect(mapsStateToprops, {fetchPosts}) (Posts);

2 个答案:

答案 0 :(得分:1)

class Posts extends Component {

    /* use did mount method because all will-methods 
       are will be deprecated in nearest future  */
    componentDidMount() {

      /* on component mount you initiate async loading data to redux store */
      this.props.fetchPosts();
      /* right after async method you cannot expect to retrieve your data immediately so this.props.posts will return [] */ 
      console.log(this.props.posts);
    }

    render() {
    /* here you getting posts from props*/
    const { posts } = this.props;

    return (
      <div>
        <h2>Posts</h2>
        /* here you render posts. After async method will be completed 
           and dispatch action with retrieved data that will cause rerender 
           of component with new props */
        {posts.map(post => (<div>post.name</div>))}
      </div>
    )
      }
    }

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

    const mapsStateToprops =  (state) =>  {
      /* first call will log an empty array of items, 
         but on second render after loading items to store they will 
         appear in component props */
      console.log("MAPSTOSTATEPROPS", state)
      return {
        posts : state.items || [];
      }

答案 1 :(得分:0)

这可能是由于fetchPost()方法的异步性质。请尝试将其记录在render()内,并使用promise处理异步性质。