Redux状态由Reducer的默认状态覆盖

时间:2018-04-20 23:39:40

标签: javascript reactjs redux react-redux

在我的react / redux应用程序中,我正在从下面的组件调度填充应用程序状态的API调用。调用成功 - 所有适当的数据都从服务器返回,并且正确填充了redux状态。但是,在正确填充状态后,它会立即被reducer中的默认状态覆盖。我无法找到问题的根源。

这是我的反应组件:

class ShowCoursesStudentParent extends React.Component<Props> {
  componentDidMount() {
    this.props.getAPIData(coursesStudentID);
  }
  render() {
    return (
      <div>
        <CourseStudentEventsParent />
        <CourseEventsParent />
        <CreateCourseEvent />
        <BigCalendarParent />
      </div>
    );
  }
}

const mapDispatchToProps = dispatch => ({
  getAPIData: coursesStudentID => dispatch(getAPIDetails(coursesStudentID))
});

const mapStateToProps = state => {
  console.log(state);
};

export default connect(mapStateToProps, mapDispatchToProps)(ShowCoursesStudentParent);

console.log(state)中的mapStateToProps会触发三次 - 首先是来自reducer默认状态的空对象,第二次是来自服务器的正确数据,然后是第三次使用来自服务器的空对象reducer的默认状态。

以下是动作创建者:

export function addAPIData(apiData: apiData) {
  return { type: ADD_API_DATA, payload: apiData };
}

export function getAPIDetails(id: number) {
  return (dispatch: Function) => {
    axios
      .get(`/get_api_data/${id}`)
      .then(response => {
        dispatch(addAPIData(response.data));
      })
      .catch(error => {
        console.log('getAPIDetails', error); //eslint-disable-line
      });
  };
}

还原器(为了简单起见,我删除了其他功能):

const apiData = (state = {}, action) => {
  if (action.type === ADD_API_DATA) {
    return action.payload;
  }
  return state;
};

const rootReducer = combineReducers({
  apiData
});

export default rootReducer;

商店:

// @flow
import { createStore, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  compose(
    applyMiddleware(thunk),
    typeof window === 'object' && typeof window.devToolsExtension !== 'undefined' ? window.devToolsExtension() : f => f
  )
);

export default store;

仅供参考 - 我正在使用flow进行类型检查。非常感谢任何帮助!

0 个答案:

没有答案