不能使用react-redux的connect函数

时间:2017-11-30 08:03:01

标签: reactjs redux react-redux

我一直在尝试将redux与材料-ui中的appbar组件一起使用。但无法正确使用连接功能。

错误消息"无法将类作为函数调用"正在控制台中显示。

我使用反应16.1.1与redux 3.7.2和react-redux 5.0.6

让我知道如何在此上下文中使用connect函数。

import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import {connect} from 'react-redux';
import * as dataTableAction from '../actions/dataTableAction';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui-icons/Menu';

const styles = theme => ({
    root: {
        width: '100%'
    },
    flex: {
        flex: 1
    },
    menuButton: {
        marginLeft: -12,
        marginRight: 20
    }
});


function ButtonAppBar(props) {
    const { classes } = props;
    return (
        <div className={classes.root}>
            <AppBar position="static">
                <Toolbar>
                    <IconButton className={classes.menuButton} color="contrast" aria-label="Menu">
                        <MenuIcon />
                    </IconButton>
                    <Typography type="title" color="inherit" className={classes.flex}>
                        Home
                    </Typography>
                    <Button color="inherit"
                            onClick={this.props.dispatch(dataTableAction.createDataTable(this.state.dataTable))}>
                        Change state
                    </Button>
                </Toolbar>
            </AppBar>
        </div>
    );
}

ButtonAppBar.propTypes = {
    classes: PropTypes.object.isRequired
};

function mapStateToProps(state, ownProps) {
    return{
        dataTable: state.dataTable
    }
}


export default withStyles(styles)(connect(mapStateToProps))(ButtonAppBar);

2 个答案:

答案 0 :(得分:4)

您需要在调用connect

之前注入样式
> doWithFunctionArg :: _ -> Int -> Int -> Int ; doWithFunctionArg f a b = f a b

<interactive>:7:22: error:
    • Found type wildcard ‘_’ standing for ‘Int -> Int -> Int’
      To use the inferred type, enable PartialTypeSignatures
    • In the type signature:
        doWithFunctionArg :: _ -> Int -> Int -> Int
    • Relevant bindings include
        doWithFunctionArg :: (Int -> Int -> Int) -> Int -> Int -> Int
          (bound at <interactive>:7:47)

您也可以使用const styledComponent = withStyles(styles)(ButtonAppBar); export default connect(mapStateToProps)(styledComponent);

compose

查看React Material UI - Export multiple higher order components了解详情

答案 1 :(得分:2)

没有撰写或重构,您可以使用以下

export default withStyles(styles)(connect(mapStateToProps) (ButtonAppBar));