developer tip

'dispatch'는 Redux에서 mapToDispatchToProps ()에 대한 인수 일 때 함수가 아닙니다.

optionbox 2020. 8. 21. 07:35
반응형

'dispatch'는 Redux에서 mapToDispatchToProps ()에 대한 인수 일 때 함수가 아닙니다.


저는 redux, react-redux 및 react를 사용하여 작은 애플리케이션을 구축하는 javascript / redux / react 초보자입니다. 어떤 이유로 mapDispatchToProps 함수를 connect (react-redux 바인딩)와 함께 사용할 때 결과 prop을 실행하려고 할 때 디스패치가 함수가 아니라는 것을 나타내는 TypeError를받습니다. 그러나 dispatch를 prop으로 호출하면 (제공된 코드의 setAddr 함수 참조) 작동합니다.

redux 문서의 TODO 앱 예제에서 mapDispatchToProps 메서드가 동일한 방식으로 설정되어있는 이유가 궁금합니다. 함수 내에서 console.log (dispatch)하면 디스패치가 유형 객체라고 말합니다. 나는 이런 식으로 디스패치를 ​​계속 사용할 수 있지만 redux를 계속하기 전에 왜 이런 일이 발생하는지 더 잘 알 것입니다. 컴파일을 위해 babel-loaders와 함께 webpack을 사용하고 있습니다.

내 코드 :

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

건배.


당신이 사용하려는 경우 mapDispatchToProps없이 mapStateToProps바로 사용 null첫 번째 인수합니다.

export default connect(null, mapDispatchToProps)(Start)


당신은 단지에 첫 번째 인수 누락 connect은 IS, 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)

사용하다

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

대신에

const StartContainer = connect(mapDispatchToProps)(Start)

나는 인수를 교환하여 해결했습니다.

export default connect(mapDispatchToProps, mapStateToProps)(Checkbox)

그것은 잘못되었습니다. mapStateToProps첫 번째 인수되어야한다 :

export default connect(mapStateToProps, mapDispatchToProps)(Checkbox)

지금 당연하게 들리지만 누군가를 도울 수 있습니다.


I needed an example using React.Component so I am posting it:

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);

Issue

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

The Arity of connect Matters: connect(mapStateToProps, mapDispatchToProps)

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

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

You may use mapDispatch without defining mapState. Pass in null in place of mapState and your component will not subject to store changes.

Connected Component Receives dispatch by Default, When No mapDispatch Is Provided

Also, your component receives dispatch because it received null for its second position for mapDispatch. If you properly pass in mapDispatch, your component will not receive 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 onSubmit That is:

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)

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

export default connect(mapStateToProps)(Checkbox)

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

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

without any mapDispatchToProps


i am using like this.. its easy to understand first argument is mapStateToProps and second argument is mapDispatchToProps in the end connect with function/class.

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

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

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

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);

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 bindActionCreators and not passing the dispatch function

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 dispatch was missing in the Error code


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

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

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

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

참고URL : https://stackoverflow.com/questions/35443167/dispatch-is-not-a-function-when-argument-to-maptodispatchtoprops-in-redux

반응형