反应导出withRouter和withStyles错误

tda*_*mon 8 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))
Run Code Online (Sandbox Code Playgroud)

Bri*_* Le 19

我相信以下代码应该可以工作:

export default withRouter(connect()(withStyles(styles)(FirstPage)))
Run Code Online (Sandbox Code Playgroud)

代替

export default connect()(withRouter(FirstPage))(withStyles(styles)(FirstPage))
Run Code Online (Sandbox Code Playgroud)

首先,connect()返回仅接受参数的函数。其次,connect()应包裹在里面withRouter()。这个问题在React Router的github文档中提出。

  • @AS490 是的,您应该可以执行`export default withRouter(withStyles(styles)(FirstPage))` (2认同)