【问题标题】:Are component refs accessible in mapDispatchToProps?mapDispatchToProps 中是否可以访问组件引用?
【发布时间】:2017-01-31 19:50:43
【问题描述】:

我有一个简单的 React 组件,它有两个输入并分派一个操作以使用输入值将项目添加到目录中。

# components/addProduct.jsx

import React from 'react'
import { connect } from 'react-redux'

const AddProduct = ({
  onClick
}) => {
  let title, price

  return (
    <form
      onSubmit= { (e) => {
        e.preventDefault()
      }}
    >
      Title: <input ref={ node => {title = node;}} type="text"/><br />
      Price: <input ref={ node => {price = node;}} type="text"/><br />
      <button onClick={onClick}>Create New Product</button>
    </form>
  )
}

function mapDispatchToProps(dispatch) {
  return {
    onClick: () => {
      console.log("Firing on click for button")
      console.log(this)               # => mapToPropsProxy
      console.log(AddProduct.refs)    # => undefined

      dispatch({                      # This will be a call to addProduct(title, price) later
        type: "ADD_PRODUCT",
        title: this.refs.title.value, # ???
        price: this.refs.price.value
      })
    }
  }
}
export default connect(null, mapDispatchToProps)(AddProduct)

我无法访问我在 AddProduct 组件中声明的引用。这很直观; AddProduct 直到connect 第一次使用mapDispatchToProps 解析并被导出时才真正存在。

那么如何访问输入值?我的架构是否不正确?

【问题讨论】:

  • 我知道我可以将调度移动到组件中,但如果我理解正确,我应该将 RENDERING 与 LOGIC 分开

标签: node.js reactjs redux


【解决方案1】:

我认为您的架构设计不正确,您的函数将被调度注入其中,因此您需要传递的变量不是上下文的一部分,如果它是这样声明的,您应该执行以下操作:

<button onClick={() => {this.props.onClick(this.refs.title.value, this.refs.price.value) }}>Create New Product</button>

和连接:

function mapDispatchToProps(dispatch) {
  return {
    onClick: (title, value) => {
      dispatch({                      # This will be a call to addProduct(title, price) later
        type: "ADD_PRODUCT",
        title,
        price
      })
    }
  }
}

【讨论】:

  • 最终工作的是&lt;button onClick={ () =&gt; {onClick(title.value, price.value) } }&gt;,谢谢!
【解决方案2】:

通常,只有在您出于某些特殊原因需要访问 DOM 时才使用 refs。使用道具和事件。比如:

<input value={title} onChange={({target:{value}}) => onTitleChanged(value)}/>

// snip

const mapDispatchToProps = dispatch => ({
    onTitleChanged: newTitle => dispatch({type: 'SOME_ACTION', value: newTitle})
})

【讨论】:

  • 但是我需要延迟调度 ADD_PRODUCT 操作,直到两个字段都被填写,这就是为什么我将它作为 onClick... 有像 PREPARE_TITLE 这样的中间操作有意义吗?您如何在 {products:[...]} 这样的简单商店中表示这一点?
  • 我想我可以在 Title Change 上将商店修改为 {products:[...], new_product: { title: 'Cookies', price: null },然后在 Price Change 上修改 price,然后在 Click 上将 new_product 折叠到产品中... redux 通常是做什么的?
猜你喜欢
  • 1970-01-01
  • 2020-10-10
  • 2010-09-06
  • 1970-01-01
  • 1970-01-01
  • 2013-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多