javascript - React-Native/Redux dispatch 在 Action 中多次触发

标签 javascript reactjs react-native redux

我正在制作一个 React/Redux 应用程序。在我的一个操作中,dispatch 在没有明显原因的情况下被调用时会触发 6-8 次。请参阅下面我的组件的操作文件中的 addMarkersRequestAddress:

export function addMarkersSuccess(response) {
  return {
    type: 'addMarkersSuccess',
    status: 'success',
    response: response,
    receivedAt: Date.now(),
  };
}

export function addMarkersFailure(error) {
  return {
    type: 'addMarkersFailure',
    status: 'error',
    error: error,
    receivedAt: Date.now(),
  };
}

export function addMarkersRequestCoordinates(submitFormData) {


  // Why is this always returning addMarkersFailure? Is it possibly related to why it always fires multiple times?
  // Same code as in virtualFenceWalk actions
  return (dispatch) => {

    console.log('running addMarkersRequestCoordinates');
    console.log('submitFormData: ',submitFormData);

    let JSONbody = JSON.stringify(submitFormData);
    console.log('JSONbody: ',JSONbody);

    fetch('http://localhost:8080/virtualFence', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSONbody
        }).then(function(response){
          dispatch(addMarkersSuccess(response));
        }).catch(function(error) {
          dispatch(addMarkersFailure(error));
        });

  }
}

export function addMarkersRequestAddress(submitFormData) {
  return (dispatch) => {

    console.log('running addMarkersRequestAddress');
    console.log('submitFormData: ',submitFormData);

    let JSONbody = JSON.stringify(submitFormData);
    console.log('JSONbody: ',JSONbody);

    // Make a request to a backend route that gets the coordinates from the Google Maps API
    fetch('http://localhost:8080/virtualFenceAddress', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSONbody
        }).then(function(response){
          console.log('addMarkersRequestAddress success');
          console.log('response: ',response);
          dispatch(addMarkersSuccess(response));
        }).catch(function(error) {
          console.log('addMarkersRequestAddress failure');
          console.log('error: ',error);
          dispatch(addMarkersFailure(error));
        });

  }

}

当此代码运行时,addMarkersSuccess 将触发 6-8 次。它在某种程度上与 dispatch 具体相关,因为如果我删除 dispatch 调用并仅保留控制台日志,addMarkersSuccess 会按预期触发一次,这就是它。它似乎也与 fetch 或异步性无关,因为如果删除 fetch 并在函数的主体中尝试相同的事情,则会出现相同的结果。

这是包裹组件的容器(因为我已经将其缩小到如何调用 dispatch 的问题,因为没有 dispatch 操作的其他部分只触发一次,也许这里的 dispatch 设置有问题?):

import React, { Component }                                             from 'react';
import PropTypes                                                        from 'prop-types';
import { StyleSheet, View, Text, TouchableOpacity, TouchableHighlight } from 'react-native';
import { bindActionCreators }                                           from 'redux';
import { connect }                                                      from 'react-redux';
import VirtualFence                                                     from '../components/VirtualFence';
import * as VirtualFenceActions                                         from '../actions/virtualFence';

const styles = StyleSheet.create({
  container: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    justifyContent: 'flex-end',
    alignItems: 'center',
  },
  back: {
    margin: 10,
    fontSize: 20,
  },
});

// Map the Redux state to props
@connect(
  state => ({
    bigState: state,
    markers: state.markers,
  }),
  dispatch => bindActionCreators(VirtualFenceActions, dispatch),
)

export default class VirtualFenceContainer extends Component {

  render() {
    return (
      <View style={styles.container}>
        <VirtualFence {...this.props} />
      </View>
    );
  }
}

这里是在组件本身中调用操作的地方:

render() {

    const {
      addMarkersRequestAddress, addMarkersSuccess, addMarkersFailure
    } = this.props;

    return (
      <View>
        <TouchableOpacity onPress={this.toggleModal}>
          <Text style={styles.bottomText}>Add markers by street address</Text>
        </TouchableOpacity>
        <Modal isVisible={this.state.isVisible}>
          <View style={{ flex: 1 }}>
            <TouchableOpacity onPress={this.toggleModal}>
              <Text style={styles.bottomText}>Hide me!</Text>
            </TouchableOpacity>
            <Form
              ref="form"
              type={Points}
              options={pointsOptions}
            />
            <Button title="Add form field" onPress={this.addFormField}></Button>
            <Button title="Delete form field" onPress={this.deleteFormField}></Button>
            <Button
              title="Submit markers"
              onPress={(argument)=>addMarkersRequestAddress(this.refs.form.getValue())}
            />
          </View>
        </Modal>
      </View>
    );
  }

虽然没有回答我的问题,但这里和其他地方的一些其他答案似乎暗示该解决方案可能与我的 configureStore.js 文件有关,所以这里是:

/* eslint global-require: 0 */

import { Platform } from 'react-native';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import reducer from './reducers';

// Presumably I need to add the other action files here somehow? Nothing seems to change as long as one file is listed...
import * as actionCreators from './actions/activityTracker';

let composeEnhancers = compose;
if (__DEV__) {
  // Use it if Remote debugging with RNDebugger, otherwise use remote-redux-devtools
  /* eslint-disable no-underscore-dangle */
  composeEnhancers = (window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ||
    require('remote-redux-devtools').composeWithDevTools)({
    name: Platform.OS,
    ...require('../package.json').remotedev,
    actionCreators,
  });
  /* eslint-enable no-underscore-dangle */
}

const enhancer = composeEnhancers(applyMiddleware(thunk));

// I think the problem with multiple dispatches may be in here
// See https://stackoverflow.com/questions/49734848/redux-dispatch-fires-multiple-times
export default function configureStore(initialState) {
  const store = createStore(reducer, initialState, enhancer);
  if (module.hot) {
    module.hot.accept(() => {
      store.replaceReducer(require('./reducers').default);
    });
  }
  return store;
}

请注意,我真的不知道这个文件在做什么。我使用 react-native-boilerplate 启动了该应用程序所以这个文件是从那里拿的。如果需要在那里进行更改,如果您能详细说明这些更改的具体作用,我们将不胜感激。

编辑 1:最初撰写此帖子时,第一次发送后的所有发送都出现错误。在应用程序的其他部分进行一些进一步的工作之后,现在所有额外的触发都记录成功。然而,基本问题(多次开火的原因)仍然存在。

编辑 2:添加了包裹组件的容器。

最佳答案

我的问题的原因原来是在我调用 combineReducers 的文件中辅助功能。我不怀疑这个文件与问题有任何关系,所以我没有发布它。对于初始状态对象中具有多个键的组件,我错误地认为我必须为每个键执行一次导入,而实际上我需要为每个 reducer 文件导入一次。我从 virtualFence reducer 导入了六个变量,每个变量都会触发 dispatch

这是错误的版本:

import { combineReducers }       from 'redux';
import nav                       from './nav';
import virtualFence              from './virtualFence';
import latitude                  from './virtualFence';
import longitude                 from './virtualFence';
import latitudeDelta             from './virtualFence';
import longitudeDelta            from './virtualFence';
import markers                   from './virtualFence';

export default combineReducers({
  nav,
  latitude,
  longitude,
  latitudeDelta,
  longitudeDelta,
  markers,
  virtualFence,
});

这是正确的版本:

import { combineReducers }           from 'redux';
import nav                           from './nav';
import virtualFence                  from './virtualFence';

export default combineReducers({
  nav,
  virtualFence,
});

关于javascript - React-Native/Redux dispatch 在 Action 中多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51479903/

相关文章:

javascript - getObject 模拟返回 0 字节文件

javascript - ng-click 不适用于我的 ionic 应用程序

javascript - React 如何在搜索中获取索引

reactjs - 在 react-router 上监听页面刷新和窗口关闭

javascript - 分享在 native android/ios 中不起作用?

android - 为什么我的 React Native 应用程序需要圆形图标?

javascript - 使用三元表达式渲染组件

javascript - 生成word文件后如何重定向php页面

javascript - Three.js EventDispatcher可以用来在类之间进行通信吗?

javascript - 在 React 中返回 array.map() 的最佳方法?