即使没有调度任何操作,Redux状态也会更改负载

时间:2016-11-21 00:01:15

标签: javascript reactjs redux react-redux flux

出于某种原因,当我加载我的webapp时,状态' currentView'设置为"科目"而不是初始值"学校"即使没有派出任何行动。为什么会这样?

actions.js

export function showSubjects(schoolId) {
  return {
    type: 'SHOW_SUBJECTS',
    schoolId
  };
}

browse.js

const initialState = {
    currentView: 'schools',
    schools: [{id: 'AAAA', name: 'aaaa'}, {id: 'BBBB', name: 'bbbb'}],
    subjects: [{id: 'CCC', name: 'ccc'}, {id: 'DDD', name: 'ddd'}]
};

function browse(state = initialState, action) {
  switch (action.type) {
    case 'SHOW_SUBJECTS':
      return {
        ...state,
        currentView: 'subjects'
      };
    default:
      return state;
  }
}

export default browse;

BrowseReduxContainer.jsx

import { connect } from 'react-redux';
import { showSubjects } from '../actions/actions';
import Browse from '../components/Browse.jsx';

function propsFilter(state) {
  switch (state.currentView) {
    case 'schools':
      return state.schools;
    case 'subjects':
      return state.subjects;
    default:
      throw new Error(`No such view: ${state.currentView}`);
  }
}

const mapStateToProps = (state) => ({
  schools: propsFilter(state)
});

const mapDispatchToProps = (dispatch) => ({
  showSubjects: (schoolId) => {
    dispatch(showSubjects(schoolId));
  }
});

const BrowseReduxContainer = connect(mapStateToProps, mapDispatchToProps)(Browse);

export default BrowseReduxContainer;

Browse.jsx

import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';

const Browse = (props) => (
  <div>
    {props.schools.map((school) => (
      <RaisedButton key={school.id} label={school.name} onClick={props.showSubjects(school.id)} />
    ))}
  </div>
);

export default Browse;

如有必要,可在此处查看其他相关文件:https://github.com/Joonpark13/serif.nu/tree/feature/browse

1 个答案:

答案 0 :(得分:3)

你的RaisedButton导致了这个问题:

<RaisedButton key={school.id} label={school.name} onClick={props.showSubjects(school.id)} />

您在showSubjects处理程序中执行onClick而不是传递引用。相反,它应该是onClick={() => props.showSubjects(school.id)},以便仅在单击后执行该功能。

作为替代方案,您还可以修改mapDispatchToProps

const mapDispatchToProps = (dispatch) => ({
  showSubjects: (schoolId) => () => {
    dispatch(showSubjects(schoolId));
  }
});