React - Redux:如何将它绑定到es6中的父容器?

时间:2016-02-12 11:01:15

标签: javascript reactjs redux

我有一个容器组件

<div ng-app="myApp">
  <div ng-controller="myctrl">
    <select ng-model="item" ng-options="option.Text for option in options track by option.Id" ng-change='selectChange()'>
    </select>
  </div>
</div>


angular.module('myApp', [])
  .controller('myctrl', ['$scope', function($scope) {

    $scope.item = {
      Id: 1
    };
    $scope.options = [{
      Text: "zero",
      Id: 0
    }, {
      Text: "one",
      Id: 1
    }, {
      Text: "two",
      Id: 2
    }, {
      Text: "three",
      Id: 3
    }, ];

    $scope.selectChange = function() {
    console.log ($scope.item.Id)
      alert($scope.item.Id);
    };
  }]);

和表达部分

import { AddQuest } from '../components/AddQuest.jsx'
import { connect } from 'react-redux'
import { addQuestActionCreator } from '../actions.js'

const mapStateToProp = (
  dispatch,
  ownProps
) => {
  return {
    onClick: () => {
      console.log(this);// <-- this represents the window object instead the AddQuest component
      dispatch(addQuestActionCreator(this.input.value)); //<-- throws : Uncaught TypeError: Cannot read property 'value' of undefined
      this.input.value = '';
    }
  }
}

export const AddQuestContainer = connect(
  undefined,
  mapStateToProp
)(AddQuest);

但每次我点击我的按钮添加任务。我有这个错误import React from 'react' import { connect } from 'react-redux' import { addQuestActionCreator } from '../actions.js' export const AddQuest = ({onClick}) => { let input; return( <div> <input type="text" ref={ node =>{ input = node; } }/> <button onClick={onClick.bind(this)}>Add quest</button> </div> ) };

我对bind(this)的理解有问题。我认为这会将表示组件的引用传递给容器组件。

为什么不是这样?

1 个答案:

答案 0 :(得分:2)

您可以通过参数和AddQuest重置输入

传递值
const mapStateToProp = (
  dispatch,
  ownProps
) => {
  return {
    onClick: (value) => {
      dispatch(addQuestActionCreator(value));
    }
  }
}

const AddQuest = ({ onClick }) => {
  let input;

  const send = () => {
    onClick(input.value)
    input.value = '';
  }

  return (
    <div>
      <input type="text" ref = { 
        (node) => { input = node }
      } />
      <button onClick={ send }>Add quest</button>
    </div>
  )
};

Example

<强>更新

arrow functions没有自己的this - 所以如果你在箭头函数.bind(this)内使用this指的是父母得分(在你的例子中它将是{ {1}}或window如果您使用strict mode),则可以使用undefined类重写您的示例

ES2015

Example