【问题标题】:Updating state after async action in react-reduxreact-redux 中的异步操作后更新状态
【发布时间】:2019-12-26 17:28:22
【问题描述】:

一般的想法是有人点击按钮,动作从服务器获取数据并调度它。状态正在更新,页面上的内容正在改变。动作看起来完全像这样:

     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)
          });
    }
    }

Reducer 非常简单:

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

主页看起来就是这样:

    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);

我原以为状态会在 componentWillReciveProps 中更新,但事实并非如此。数据将在一段时间后被获取,所以我不能像那样设置状态。知道怎么做吗?

【问题讨论】:

    标签: javascript reactjs redux


    【解决方案1】:

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

    1. 额外的status 标志
    2. 其他操作

    工作流程希望:

    1. 获取数据,调度一个动作,将status设置为'fetching'
    2. 如果获取成功,派发一个动作,将status设置为'success'
    3. 如果感染失败,调度一个动作,将status设置为'error'

    延伸阅读:Redux :: Async actions

    【讨论】:

    • 谢谢伙计!这完美!我可以整天阅读有关 React 的信息,但我从不喜欢 Redux 文档,但我肯定会更频繁地阅读它们 :)
    • 很高兴我能帮上忙 :)
    猜你喜欢
    • 1970-01-01
    • 2017-04-20
    • 2022-08-17
    • 2019-08-18
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    相关资源
    最近更新 更多