Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 集中化操作在React/Redux中不起作用_Reactjs_Redux - Fatal编程技术网

Reactjs 集中化操作在React/Redux中不起作用

Reactjs 集中化操作在React/Redux中不起作用,reactjs,redux,Reactjs,Redux,当用户从一个组件转到另一个组件时,我需要执行一些清理。为了保持简单一致,我创建了一个集中的动作创建者,如下所示: import { cleanUpX } from 'moduleX'; import { cleanUpY } from 'moduleY'; import { cleanUpZ } from 'moduleZ'; export const cleanUp = () => { cleanUpX(); cleanUpY(); cleanUpZ(); } 然

当用户从一个组件转到另一个组件时,我需要执行一些清理。为了保持简单一致,我创建了一个集中的动作创建者,如下所示:

import { cleanUpX } from 'moduleX';
import { cleanUpY } from 'moduleY';
import { cleanUpZ } from 'moduleZ';

export const cleanUp = () => {

   cleanUpX();
   cleanUpY();
   cleanUpZ();
}
然后,我在组件的componentWillUnmount生命周期方法中调用此操作创建者:

class MyComponent1 extends Component {

   ... Code omitted for brevity
   componentWillUnmount() {

      this.props.actions.cleanUp();
   }
}
即使我点击了清理和它里面的每个动作创建者,我也没有点击它们各自的减速器

换句话说,我看到我点击了cleanUpY,但它结束于此,我从未点击减速器来执行实际的状态更改

但是,如果我执行以下操作,则效果良好:

class MyComponent1 extends Component {

   ... Code omitted for brevity
   componentWillUnmount() {

      this.props.actions.cleanUpX();
      this.props.actions.cleanUpY();
      this.props.actions.cleanUpZ();
   }
}

我在这里遗漏了什么?

什么都没有发生,因为导入的动作创建者与this.props.actions上的对应者不同,没有绑定分派,因此调用它们只会返回一个动作对象,而不会触发减缩器

您可以手动将dispatch注入到您的道具中,然后将其传递给清理功能,但最简单的解决方案是安装,并按如下方式编写动作创建者:

export const cleanUp = () => (dispatch, getState) => {
  dispatch(cleanupX());
  dispatch(cleanupY());
  dispatch(cleanupZ());
};
然后在connect处绑定它,就像为其他动作创建者绑定一样,并使用this.props.actions.cleanUp从组件调用它

redux thunk的安装非常简单,只需安装npm包并将其添加到商店的中间件:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import yourReducer from ...;

const store = createStore(
  yourReducer,
  applyMiddleware(thunk)
);