mapDispatchToProps with react-redux'connect()和类组件

时间:2017-06-21 06:09:13

标签: reactjs react-redux

我正在密切关注react-redux的教程,但决定将我的演示组件编写为一个类。正如您在下面的代码中看到的,我编写了一个submitHandler,它应该调用react-redux'connect()映射的submitHandler。但是当我调用它时,会产生TypeError: Cannot read property 'props' of null

有什么建议吗?

容器组件

import { connect } from 'react-redux'
import New from './New'
import { newEntry } from '../../store/actions'

function mapStateToProps(state) {
  return {
    value: state.currentEntries[state.currentEntries.length - 1].value,
    min: state.currentEntries[state.currentEntries.length - 1].value,
    max: 148
  }
}

function mapDispatchToProps(dispatch) {
  return {
    onSubmit: (date, value) => {
      dispatch(newEntry(date, value))
    }
  }
}

const NewContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(New)

export default NewContainer

演示文稿

import React from 'react'
import moment from 'moment'

export default class Chart extends React.Component {
  submitHandler(e) {
    e.preventDefault()

    // BUG: Results in "TypeError: Cannot read property 'props' of null"
    this.props.onSubmit(this.date.value, this.number.value)

    this.date.value = moment().format('YYYYY-MM-DD')
    this.number.value = this.props.min
  }

  render() {
    const { value, min, max } = this.props

    return (
      <form className="New" onSubmit={this.submitHandler}>
        <input type="date" ref={node => { this.date = node}} defaultValue={moment().format('YYYYY-MM-DD')} />
        <input type="number" ref={node => { this.number = node }} min={min} max={max} defaultValue={value} />
        <button>Save</button>
      </form>
    )
  }
}

2 个答案:

答案 0 :(得分:2)

您只需要bind提交处理程序:

 <form className="New" onSubmit={this.submitHandler}>

应该是:

 <form className="New" onSubmit={this.submitHandler.bind(this)}>

或者:

 <form className="New" onSubmit={(e) => this.submitHandler(e)}>

class组件的区别在于方法不会自动绑定this

答案 1 :(得分:1)

试试这个!

&#13;
&#13;
import React from 'react'
import moment from 'moment'

export default class Chart extends React.Component {
  submitHandler(e) {
    e.preventDefault()

    // BUG: Results in "TypeError: Cannot read property 'props' of null"
    this.props.onSubmit(this.date.value, this.number.value)

    this.date.value = moment().format('YYYYY-MM-DD')
    this.number.value = this.props.min
  }

  render() {
    const { value, min, max } = this.props

    return (
      <form className="New" onSubmit={this.submitHandler.bind(this)}>
        <input type="date" ref={node => { this.date = node}} defaultValue={moment().format('YYYYY-MM-DD')} />
        <input type="number" ref={node => { this.number = node }} min={min} max={max} defaultValue={value} />
        <button>Save</button>
      </form>
    )
  }
}
&#13;
&#13;
&#13;