首页 > 解决方案 > Redux 容器不知道“this”是什么

问题描述

我一直试图弄清楚为什么我的容器不知道“这个”是什么。

如果我将容器更改为组件,那么它一切正常。

这个组件完美地工作并在它到达商店时改变状态

    class testCard extends Component {


       test= (event) => {
           console.log("!!!!!!!!!!!!!!"); // Shows
           this.props.testAction(); // This works
       }

       render(){
       return (
       <Card>
           <CardActionArea onClick={this.test}>
               ... // Card stuff
           </CardActionArea>
           <CardActions>
       </Card>)
       }
   }


   const mapStateToProps = (state) => {
       return {

      }
   }

   const mapDispatchToProps = (dispatch) => {
       return bindActionCreators(
       {
            testAction:   testAction()
        }, dispatch)
   }
   export default connect(mapStateToProps, mapDispatchToProps) (testCard);

下面的代码不知道'this'是什么并且会抛出错误。

   const testCard = (props) => {

    let test= (event) => {
        console.log("!!!!!!!!!!!!!!"); // Shows
        this.props.testAction(); // This errors saying cannot find props of undefined
    }


    return (
    <Card>
        <CardActionArea onClick={test}>
            ... // Card stuff
        </CardActionArea>
        <CardActions>
    </Card>)
  }


  const mapStateToProps = (state) => {
     return {

     }
  }

  const mapDispatchToProps = (dispatch) => {
     return bindActionCreators({
         testAction:  testAction()
     }, dispatch)
   }
   export default connect(mapStateToProps, mapDispatchToProps) (testCard);

标签: javascriptreactjsreduxreact-redux

解决方案


简而言之,您必须在第二个示例中调用 props.testAction() 。它使用 ES6 箭头函数。 https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4

此外,当您将箭头函数用于反应组件时,您不需要 render() 方法(当您使用基于类的组件时需要渲染,即扩展 React.Component,然后您需要实现它),您在箭头函数中需要的只是返回您的结果,即 jsx 数据。

https://medium.com/@yassimortensen/container-vs-presentational-components-in-react-8eea956e1cea


推荐阅读