反应导出withRouter和withStyles错误

时间:2018-11-03 03:02:04

标签: reactjs redux material-ui

我正在使用react以及redux和material-ui来制作组件。我正在尝试编写导出语句export default connect()(withRouter(FirstPage))(withStyles(styles)(FirstPage))

但是,这似乎不起作用,我看到一条错误消息

TypeError: Cannot set property 'props' of undefined

this.props = props;

此错误引用了我的一个node_modules。

这是我的完整代码:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import {withRouter} from 'react-router-dom'
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';

const styles = theme =>({
    root: {
        maxWidth: 345,
    },

})
class FirstPage extends Component {
    state = {
        feeling: ''
    }

    //This function will dispatch the users response to index.js
    //The dispatch type here is 'SET_FEELING'
    submitData=(event) => {
        event.preventDefault();
        this.props.dispatch({type: 'SET_FEELING', payload: this.state})
        this.changeLocation();
    }

    //This function will update the local state with the users response
    handleChange= (event) => {
        this.setState({
            feeling: event.target.value
        })
    }

    //This function will change the current url when a button is clicked
    changeLocation= ()=> {
        this.props.history.push('/secondPage')
    }

    render(){
        const { classes } = this.props;

        return(
            <div>
                <Card >
                    <CardContent className={classes.root}>

                        <form>
                        <input onChange={this.handleChange} placeholder='How are you feeling' value={this.state.feeling} />
                        </form>
                    </CardContent>
                    <CardActions>
                        <Button onClick={this.submitData}>Submit</Button>
                    </CardActions>
                </Card>
            </div>
        )
    }
}

//this export connects the component to the reduxStore as well as allowing us to use the history props
export default connect()(withRouter(FirstPage))(withStyles(styles)(FirstPage))

1 个答案:

答案 0 :(得分:7)

我相信以下代码应能工作:

export default withRouter(connect()(withStyles(styles)(FirstPage)))

代替

export default connect()(withRouter(FirstPage))(withStyles(styles)(FirstPage))

首先,connect()返回仅接受参数的函数。其次,connect()应该包裹在withRouter()内。这个问题在React Router的github文档中有所说明。