React Native Redux调度不是函数,调度是Object的实例

时间:2018-10-22 10:48:00

标签: reactjs react-native redux react-redux

调用dispatch时出现错误-“ dispatch不是函数,dispatch是Object的实例” 我已经连接了mapDispatchToProps,但我不知道该如何解决(我是反应和还原的新手) 这是我的代码:

import React from 'react';
import {Text, View} from 'react-native';
import Slider from 'react-native-slider';
import { connect } from "react-redux";

class SliderComponent extends React.Component{
    constructor(props){
        super(props)

        this.state={
            sliderValue: this.props.val,
            type: this.props.sliderText,
        }
    }

    render(){
        return(
            <View style={{alignContent: 'center', flexDirection: 'row', padding: 10, justifyContent: 'center'}}>
                <Text style={{color: 'white', flex: 1, alignContent: 'center', justifyContent: 'center', fontSize: 20, fontWeight: 'bold'}}>{this.state.type}</Text>
                <Slider style={{width: 300, padding: 30, flex: 4}} thumbTintColor='white' step={1} value={this.state.sliderValue} minimumValue={this.props.min} maximumValue={this.props.max} minimumTrackTintColor='#F87883' onValueChange={val => {
                    this.setState({sliderValue: val})
                }
            }
            onSlidingComplete={ val =>
                this.props.changeSliderValue(this.state.type, this.state.sliderValue)
            }
            >
                    </Slider>
                <Text style={{color: 'white', flex: 1, alignContent: 'center', justifyContent: 'center', fontSize: 20, fontWeight: 'bold'}}>{this.state.sliderValue}</Text>
            </View>
        )
    }
};

const mapDispatchToProps = (dispatch) => {
    return{
        changeSliderValue: (type, value) => { dispatch({type: type, value: value}) }
    }
}

export default connect(
mapDispatchToProps
)(SliderComponent);

3 个答案:

答案 0 :(得分:1)

connect是用错误的方式实现的,您的实际代码是

const mapDispatchToProps = (dispatch) => {
  return {
    changeSliderValue: (type, value) => { 
      dispatch({type: type, value: value});
    }
  }
}

export default connect(mapDispatchToProps)(SliderComponent);

,但是connect的实际语法是,第一个参数mapStateToProps函数,第二个参数是mapDispatchToProps。请按如下所示更改连接代码。

const mapDispatchToProps = (dispatch) => {
  return {
    changeSliderValue: (type, value) => { 
      dispatch({type: type, value: value});
    }
  }
}

const mapStateToProps = (state) => null;

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

答案 1 :(得分:0)

mapDispatchToProps的{​​{1}}函数中,第一个参数 您所指的是connect-对象。

Redux store

https://gist.github.com/heygrady/c6c17fc7cbdd978f93a746056f618552

const mapDispatchToProps = (
  state,  // This is Redux state object
  dispatch,
) => {

就像在此示例中一样,第二个参数就是您想要的。

答案 2 :(得分:0)

似乎添加了mapStateToProps使其起作用