【问题标题】:ReactJS updating state from childReactJS 从孩子更新状态
【发布时间】:2014-05-14 23:34:14
【问题描述】:

我正在使用 ReactJS 和 CoffeeScript (:

实际上我有一个处理状态的组件 A。状态字段被传递给孩子(在该示例中称为 myChild)。子需要从父状态更新一些值。

我怎样才能以 ReactJS 的方式做到这一点?

A = React.createClass
  getInitialState: 
    mystate: {test: 1}

  render: ->
    myChild {param: @state.mystate}


myChild = React.createClass
  render: ->
    React.DOM.div {onClick: @change}, @props.param.test

  change: ->
    @props.param.test += 1 # WRONG WRONG WRONG
    ajax("/..../", JSON.stringify(@props.param))
      .done(@onDone).fail(...)

  onDone: ->
    console.log "Hum..."

评论:

-@props.param.test 不能那样改变(为了连贯性,它应该是不可变的)。

-@props.param 实际上是组件 A 状态中的对象,因此应该使用 @setState 更新它,这是不可能的,因为我们在子组件中:(

我怎样才能清除这个以拥有一个好的 ReactJS 组件?

保罗?你还会帮我吗? :D

【问题讨论】:

  • 我想解决方案是:1) Create a clone of @props.param then update @props.param.test 2) Do the ajax request 3) Reload the parent component ? But how to reload the parent ?

标签: coffeescript reactjs


【解决方案1】:

父母是真相的来源,所以孩子需要告诉父母改变它的状态。将一个回调从父级传递给子级,并让子级调用它。

在 React 的文档中有一个关于 communicating between components 的示例,可能也有帮助。

A = React.createClass
  getInitialState: ->
    mystate: {test: 1}

  incrementTest: ->
    @setState {mystate: {test: @state.mystate.test + 1}}

  render: ->
    myChild {onChange: @incrementTest, param: @state.mystate}


myChild = React.createClass
  render: ->
    React.DOM.div {onClick: @change}, @props.param.test

  change: ->
    @props.onChange
    ajax("/..../", JSON.stringify(@props.param))
      .done(@onDone).fail(...)

  onDone: ->
    console.log "Hum..."

【讨论】:

  • 很好,我忘记了回调解决方案:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-05
  • 2015-06-14
  • 1970-01-01
  • 2015-01-22
  • 2016-10-02
  • 2017-06-03
相关资源
最近更新 更多