【问题标题】:Reducer or Action not working减速器或动作不起作用
【发布时间】:2017-11-22 11:30:23
【问题描述】:

我在这里遇到了问题,我已经做 redux 大约 2 周了。

我正在尝试创建一个加载程序,因此我正在尝试获取 isFetching 状态。使用 thunk,我正在执行 ajax 获取,并调度加载状态。

调用了调度,因为我可以在控制台中看到。

在组件挂载之前,它假设调用 FETCH_PROFILE,并且 isFetching 设置为 true,但是当我在 console.log(this.props.profile.isFetching) 时,它返回 false。

与 FETCH_PROFILE_SUCCESS 相同,它不会更新 this.props.profile。 (或者因为它没有重新渲染......所以我看不到它)

我已经在这个简单的事情上工作了几个小时,但我不知道为什么它没有更新......我确定我在某个地方犯了一些错误,但不知道是什么。

export const FETCH_PROFILE = 'FETCH_PROFILE';
export const FETCH_PROFILE_SUCCESS = 'FETCH_PROFILE_SUCCESS';
export const FETCH_PROFILE_FAIL = 'FETCH_PROFILE_FAIL';


export function getUserProfile() {


           return (dispatch) => {
                dispatch(getUserProfileStart());
                const config2 = {
                    method: 'GET',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    credentials: 'include',
                    body: ``,
                };

              fetch('http://api.example.com/profile/',config2)
              .then((resp) => resp.json())
              .then(function(data) {        

               dispatch(getUserProfileSuccess(data));
               return 0;

            }).catch(function(error){

                return dispatch({type: FETCH_PROFILE_FAIL});
            })

}
}


function getUserProfileSuccess(data) {
    return {
        type: FETCH_PROFILE_SUCCESS,
        isFetching: false,
        payload: data
    }
}

function getUserProfileStart() {
    return {
        type: FETCH_PROFILE,
        isFetching: true
    }
}

我的减速器

import {
  FETCH_PROFILE,
  FETCH_PROFILE_SUCCESS,
  FETCH_PROFILE_FAIL
} from '../actions/profile';


export default function userProfile(state={isFetching: false}, action) {


  switch(action.type) {

      case FETCH_PROFILE:

        return {...state, isFetching: true}

      case FETCH_PROFILE_SUCCESS:

         return {...state, isFetching: false, data: action.payload}

      case FETCH_PROFILE_FAIL:
         return { ...state, isFetching: false };

      default:
        return state


  }
}

我的组件。

import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import {connect } from 'react-redux';
import * as profileActions from '../../actions/profile';
import {bindActionCreators} from 'redux';  

class ProfilePage extends React.Component {

    constructor(props) {
        super(props);

        this.getUserProfile = this.getUserProfile.bind(this);

    }

    componentWillMount() {

      this.props.actions.getUserProfile();
    }


  render() {
    console.log('Checking isFetching State', this.props.profile.isFetching);
    return (

      <div>

       some text here.
      </div>

    );
  }
}


function mapStateToProps(state) {
  console.log('Mapping Stat', state.profile);
  return {
    profile: state.userProfile
  };
}

function mapDispatchToProps(dispatch) {  
  return {
    actions: bindActionCreators(profileActions, dispatch)
  };
}


export default connect(mapStateToProps, mapDispatchToProps)(withStyles(s)(ProfilePage));

我的联合减速机...

import userProfile from './profile';
//some other imports...
export default combineReducers({

  userProfile,
  //other reducers that works...
});

【问题讨论】:

    标签: reactjs react-redux


    【解决方案1】:

    试试这个: 创建商店时在索引处

    export const store = createStore(
        combineReducer,
        applyMiddleware(thunk) // choose you middleware....
        //initial state as per need
    );

    在减速器处:

    import {
      FETCH_PROFILE,
      FETCH_PROFILE_SUCCESS,
      FETCH_PROFILE_FAIL
    } from '../actions/profile';
    
    
    export default function userProfile(state= {
      initialized: true,
      init:false,
      success:false,
      fail:false,
      
    }, action) {
      switch(action.type) {
    
          case FETCH_PROFILE:{
           const message = action.message; 
              return Object.assign({}, state, { 
                 init:true,
                 success:false,
                 fail:false,
                 data:message,
              })
    }
          }
    
          case FETCH_PROFILE_SUCCESS:{ 
          const data = action.data; 
              return Object.assign({}, state, { 
                 init:false,
                 success:true,
                 fail:false,
                 data:data,
              })
    }
    
          case FETCH_PROFILE_FAIL:{ 
          const err = action.err; 
              return Object.assign({}, state, { 
                 init:false,
                 success:false,
                 fail:true,
                 data:err,
              })
    }
    
          default:
            return state
    
    
      }
    }

    在组件处:

    import React from 'react';
    //use can use this if required.
    //import withStyles from 'isomorphic-style-loader/lib/withStyles';
    import {connect } from 'react-redux';
    import { profileActions}  from '../../actions/profile';
    //import {bindActionCreators} from 'redux';  
    
    class ProfilePage extends React.Component {
    
        constructor(props) {
            super(props);
            this.state{
            success:false;
            }
        }
    
        componentWillMount() {
    
          this.props.getUserProfile();
        }
        
        componentWillReciveProps(nextprop){
         if(nextprop.success===true){
         this.setState({success==true});
         }
        }
    
      render() {
        
        return (
          {(this.state.success)?<div>this.props.profile.data.yourdata</div>:<div>Loading....</div>}
        );
      }
    }
    
    
    function mapStateToProps(state) {
       return {
        profile: state.userProfile
      };
    }
    
    
    
    
    export default connect(mapStateToProps,{profileActions
    })(ProfilePage);

    在行动中:

    export const FETCH_PROFILE = 'FETCH_PROFILE';
    export const FETCH_PROFILE_SUCCESS = 'FETCH_PROFILE_SUCCESS';
    export const FETCH_PROFILE_FAIL = 'FETCH_PROFILE_FAIL';
    
    
    export function getUserProfile() {
    
    
               return (dispatch) => {
                    dispatch(getUserProfileStart(const message:"fetch start"));
                    const config2 = {
                        method: 'GET',
                        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                        credentials: 'include',
                        body: ``,
                    };
    
                  fetch('http://api.example.com/profile/',config2)
                  .then((resp) => resp.json())
                  .then(function(data) {        
    
                   dispatch(getUserProfileSuccess(data));
                   return 0;
    
                }).catch(function(error){
    
                    return dispatch(getUserProfileError(error));
                })
    
    }
    }
    
    
    function getUserProfileSuccess(data) {
        return {
            type: FETCH_PROFILE_SUCCESS,
            data
        }
    }
    
    function getUserProfileStart(message) {
        return {
            type: FETCH_PROFILE,
            message
        }
    }
    
    function getUserProfileError(err) {
        return {
            type: FETCH_PROFILE,
            err
        }
    }

    【讨论】:

    • 检查上面的代码。这应该可以解决您的问题
    猜你喜欢
    • 2018-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-02
    • 1970-01-01
    • 2020-02-13
    • 2014-05-21
    • 2021-01-13
    相关资源
    最近更新 更多