Javascript 当 Redux 中 mapToDispatchToProps() 的参数时,'dispatch' 不是函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35443167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:43:54  来源:igfitidea点击:

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

javascriptreactjsreduxreact-redux

提问by sully

I am a javascript/redux/react beginner building an small application with redux, react-redux, & react. For some reason when using mapDispatchToProps function in tandem with connect (react-redux binding) I receive a TypeError indicating that dispatch is not a function when I try to execute the resulting prop. When I call dispatch as a prop however (see the setAddr function in the provided code) it works.

我是一名 javascript/redux/react 初学者,正在使用 redux、react-redux 和 react 构建一个小型应用程序。出于某种原因,当我将 mapDispatchToProps 函数与 connect(react-redux 绑定)结合使用时,我收到一个 TypeError,表明当我尝试执行生成的 prop 时,dispatch 不是一个函数。但是,当我将 dispatch 作为道具调用时(请参阅提供的代码中的 setAddr 函数),它可以工作。

I'm curious as to why this is, in the example TODO app in the redux docs the mapDispatchToProps method is setup the same way. When I console.log(dispatch) inside the function it says dispatch is type object. I could continue to use dispatch this way but I would feel better knowing why this is happening before I continue any further with redux. I am using webpack with babel-loaders to compile.

我很好奇为什么会这样,在 redux 文档的示例 TODO 应用程序中,mapDispatchToProps 方法的设置方式相同。当我在函数内 console.log(dispatch) 时,它说 dispatch 是类型对象。我可以继续以这种方式使用 dispatch,但在我继续使用 redux 之前,知道为什么会发生这种情况会感觉更好。我正在使用带有 babel-loader 的 webpack 进行编译。

My Code:

我的代码:

import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { setAddresses } from '../actions.js';
import GeoCode from './geoCode.js';
import FlatButton from 'material-ui/lib/flat-button';

const Start = React.createClass({
    propTypes: {
        onSubmit: PropTypes.func.isRequired
    },

    setAddr: function(){
        this.props.dispatch(
            setAddresses({
                pickup: this.refs.pickup.state.address,
                dropoff: this.refs.dropoff.state.address
            })
        )   

    },

    render: function() {
        return (
            <div>
                <div className="row">
                    <div className="col-xs-6">
                        <GeoCode ref='pickup' />
                    </div>
                    <div className="col-xs-6">
                        <GeoCode ref='dropoff' />
                    </div>
                </div>
                <div className="row">
                    <div className="col-xs-6">
                        <FlatButton 
                            label='Does Not Work'
                            onClick={this.props.onSubmit({
                                pickup: this.refs.pickup.state.address,
                                dropoff: this.refs.dropoff.state.address
                            })} 
                            />
                    </div>
                    <div className="col-xs-6">
                        <FlatButton 
                            label='Works'
                            onClick={this.setAddr} 
                            />
                    </div>
                </div>
            </div>
        );
    }
})

const mapDispatchToProps = (dispatch) => {
    return {
        onSubmit: (data) => {
            dispatch(setAddresses(data))
        }
    }
}

const StartContainer = connect(mapDispatchToProps)(Start)

export default StartContainer

Cheers.

干杯。

回答by inostia

If you want to use mapDispatchToPropswithout a mapStateToPropsjust use nullfor the first argument.

如果你想使用mapDispatchToProps而没有mapStateToPropsnull用于第一个参数。

export default connect(null, mapDispatchToProps)(Start)

export default connect(null, mapDispatchToProps)(Start)

回答by Brandon

You are just missing the first argument to connect, which is the mapStateToPropsmethod. Excerpt from the Redux todo app:

您只是缺少 的第一个参数connect,即mapStateToProps方法。摘自 Redux 待办事项应用程序:

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

回答by Ann

Use

const StartContainer = connect(null, mapDispatchToProps)(Start) 

instead of

代替

const StartContainer = connect(mapDispatchToProps)(Start)

回答by Amit Mittal

I solved it by interchanging the arguments, I was using

我通过交换参数解决了它,我正在使用

export default connect(mapDispatchToProps, mapStateToProps)(Checkbox)

which is wrong. The mapStateToPropshas to be the first argument:

这是错误的。在mapStateToProps有可能成为第一个参数:

export default connect(mapStateToProps, mapDispatchToProps)(Checkbox)

It sounds obvious now, but might help someone.

现在听起来很明显,但可能会帮助某人。

回答by wgao19

Issue

问题

Here are a couple of things to notice in order to understand the connected component's behavior in your code:

为了理解代码中连接组件的行为,需要注意以下几点:

The Arity of connectMatters: connect(mapStateToProps, mapDispatchToProps)

事物的多样性connectconnect(mapStateToProps, mapDispatchToProps)

React-Redux calls connectwith the first argument mapStateToProps, and second argument mapDispatchToProps.

React-Reduxconnect使用第一个参数mapStateToProps和第二个参数调用mapDispatchToProps

Therefore, although you've passed in your mapDispatchToProps, React-Redux in fact treats that as mapStatebecause it is the first argument. You still get the injected onSubmitfunction in your component because the return of mapStateis merged into your component's props. But that is not how mapDispatchis supposed to be injected.

因此,尽管您已经传入了mapDispatchToProps,React-Redux 实际上将其视为mapState因为它是第一个参数。您仍然会onSubmit在组件中获得注入的函数,因为 的返回mapState已合并到组件的 props 中。但这不是mapDispatch应该如何注入。

You may use mapDispatchwithout defining mapState. Pass in nullin place of mapStateand your component will not subject to store changes.

您可以在mapDispatch不定义的情况下使用mapState。转至null代替mapState你的组件将不会以店面为准变化。

Connected Component Receives dispatchby Default, When No mapDispatchIs Provided

连接的组件dispatch默认接收,当没有mapDispatch提供时

Also, your component receives dispatchbecause it received nullfor its second position for mapDispatch. If you properly pass in mapDispatch, your component will not receive dispatch.

此外,您的组件收到dispatch是因为它收到nullmapDispatch. 如果您正确传入mapDispatch,您的组件将不会收到dispatch.

Common Practice

常见做法

The above answers why the component behaved that way. Although, it is common practice that you simply pass in your action creator using mapStateToProps's object shorthand. And call that within your component's onSubmitThat is:

以上回答了为什么组件会这样。虽然,通常的做法是简单地使用mapStateToProps的对象速记传入您的动作创建者。并在您的组件中调用它,onSubmit即:

import { setAddresses } from '../actions.js'

const Start = (props) => {
  // ... omitted
  return <div>
    {/** omitted */}
    <FlatButton 
       label='Does Not Work'
       onClick={this.props.setAddresses({
         pickup: this.refs.pickup.state.address,
         dropoff: this.refs.dropoff.state.address
       })} 
    />
  </div>
};

const mapStateToProps = { setAddresses };
export default connect(null, mapDispatchToProps)(Start)

回答by Amio.io

I needed an example using React.Componentso I am posting it:

我需要一个例子,React.Component所以我发布了它:

import React from 'react';
import * as Redux from 'react-redux';

class NavigationHeader extends React.Component {

}

const mapStateToProps = function (store) {
    console.log(`mapStateToProps ${store}`);
    return {
        navigation: store.navigation
    };
};

export default Redux.connect(mapStateToProps)(NavigationHeader);

回答by Codiee

Sometime this error also occur when you change the order of Component Function while passing to connect.

有时,当您在传递到连接时更改组件函数的顺序时也会发生此错误。

Incorrect Order:

错误的顺序:

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

Correct Order:

正确的顺序:

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

回答by imbatman

A pitfall some might step into that is covered by this question but isn't addressed in the answers as it is slightly different in the code structure but returns the exact same error.

这个问题涵盖了一些人可能会遇到的陷阱,但在答案中没有解决,因为它在代码结构中略有不同,但返回完全相同的错误。

This error occurs when using bindActionCreatorsand not passing the dispatchfunction

使用bindActionCreators和不传递dispatch函数时发生此错误

Error Code

错误代码

import someComponent from './someComponent'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { someAction } from '../../../actions/someAction'

const mapStatToProps = (state) => {
    const { someState } = state.someState

    return {
        someState
    }
};

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        someAction
    });
};

export default connect(mapStatToProps, mapDispatchToProps)(someComponent)

Fixed Code

固定码

import someComponent from './someComponent'
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { someAction } from '../../../actions/someAction'

const mapStatToProps = (state) => {
    const { someState } = state.someState

    return {
        someState
    }
};

const mapDispatchToProps = (dispatch) => {
    return bindActionCreators({
        someAction
    }, dispatch);
};

export default connect(mapStatToProps, mapDispatchToProps)(someComponent)

The function dispatchwas missing in the Error code

dispatch错误代码中缺少该功能

回答by Sachin Metkari

React-redux 'connect' function accepts two arguments first is mapStateToProps and second is mapDispatchToProps check below ex.

React-redux 'connect' 函数接受两个参数,第一个是 mapStateToProps,第二个是 mapDispatchToProps 检查下面的例子。

export default connect(mapStateToProps, mapDispatchToProps)(Index);`

export default connect(mapStateToProps, mapDispatchToProps)(Index);`

If we don't want retrieve state from redux then we set null instead of mapStateToProps.

如果我们不想从 redux 中检索状态,那么我们设置 null 而不是 mapStateToProps。

export default connect(null, mapDispatchToProps)(Index);

export default connect(null, mapDispatchToProps)(Index);

回答by Serge Nikolaev

When you do not provide mapDispatchToPropsas a second argument, like this:

当您不提供mapDispatchToProps作为第二个参数时,如下所示:

export default connect(mapStateToProps)(Checkbox)

then you are automatically getting the dispatch to component's props, so you can just:

然后你会自动获取组件的 props 的调度,所以你可以:

class SomeComp extends React.Component {
  constructor(props, context) {
    super(props, context);
  }
  componentDidMount() {
    this.props.dispatch(ACTION GOES HERE);
  }
....

without any mapDispatchToProps

没有任何 mapDispatchToProps