即使没有分派任何操作,Redux 状态也会在加载时更改

Posted

技术标签:

【中文标题】即使没有分派任何操作,Redux 状态也会在加载时更改【英文标题】:Redux state changes on load even though no action has been dispatched 【发布时间】:2017-04-04 07:14:39 【问题描述】:

由于某种原因,当我加载我的 web 应用程序时,状态“currentView”设置为“subjects”而不是初始值“schools”,即使没有调度任何操作。为什么会这样?

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】:

您的 RaisedButton 会导致问题:

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

您在 onClick 处理程序中执行 showSubjects 而不是传递引用。相反,它应该是onClick=() =&gt; props.showSubjects(school.id),以便该函数仅在单击后执行。

您也可以修改mapDispatchToProps

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

【讨论】:

不敢相信我错过了回调。谢谢。

以上是关于即使没有分派任何操作,Redux 状态也会在加载时更改的主要内容,如果未能解决你的问题,请参考以下文章

从非反应文件分派操作时 Redux 状态未更新

无法使用react-native app中的redux-persist检查索引/主文件上是否已加载持久状态

Redux 状态未在 Redux DevTool 中更新

React Native Redux:动作分派,返回结果

当用户访问未分派操作的页面时,反应应用程序崩溃

redux dispatch 多次触发