在react-redux中异步操作后更新状态

tus*_*ior 5 javascript reactjs redux

总体思路是,有人单击按钮,操作从服务器获取数据并发送它。状态正在更新,页面上的内容正在发生变化。该动作看起来完全像这样:

     export function getPosts(page){
     return function(dispatch){
      axios.get(`${ROOT_URL}/home?page=${page}`)
          .then(response => {
            dispatch ({
            type: FETCH_POSTS,
            payload: response.data        
          })
          })
          .catch((error) => {
            console.log(error)
          });
    }
    }
Run Code Online (Sandbox Code Playgroud)

减速器非常简单:

      export default function(state={}, action){
      switch(action.type){
        case FETCH_POSTS:
        return {posts: action.payload, ...state};
      }
      return state;
    }
Run Code Online (Sandbox Code Playgroud)

主页看起来就像这样:

    import React, { Component } from 'react';
    import * as actions from '../actions';
    import RequireAuth from './auth/require_auth';
    import { connect } from 'react-redux';
    import { compose } from 'redux';
    class Home extends Component {

    constructor(props) {
      super(props);
      this.state = {
        posts: 'loading....',
      };
      this.props.getPosts();
    }  
    handlePage(){
    console.log(this.props);
    let page = 3;
    this.props.getPosts();
    }

    componentWillReceiveProps(nextProps){
      let posts = nextProps.posts.posts.map((post) => {
      return (<li key={post._id}>{post.date}</li>)
      });
      this.setState({posts: posts});

    }
    shouldComponentUpdate(nextState, nextProps){
    console.log(nextProps.posts, nextState.posts);
    return true;
    }
      render(){
        return(
          <div>
            {this.state.posts}
            <button onClick={this.handlePage.bind(this)}>change something</button>
          </div>
          )
    }
    }

    function mapStateToProps(state){
      return {posts: state.post}
    }

    export default connect(mapStateToProps, actions)(Home);
Run Code Online (Sandbox Code Playgroud)

我以为状态会在 componentWillReciveProps 中更新,但这并没有发生。数据将在一段时间后获取,因此我无法像那样设置状态。知道如何做到这一点吗?

Non*_*ial 3

对于异步操作,有两种可能的方式:

  1. 一个额外的status标志
  2. 额外的行动

工作流程希望:

  1. 获取数据,调度一个动作,该动作设置status'fetching'
  2. 如果获取成功,则分派一个操作,该操作设置status'success'
  3. 如果 fecting 失败,则分派一个操作,该操作设置status'error'

进一步阅读:Redux :: 异步操作