【问题标题】:Get live updated data with ajax in a react component在反应组件中使用 ajax 获取实时更新的数据
【发布时间】:2016-04-02 07:39:55
【问题描述】:

故事:

用户单击“添加”,它将数据库中的值设置为true。点击“删除”,将数据库中的同一列更新为false:

def add
  u = User.find(1)
  u.foo = true
  u.save
  u.reload
  head :ok
end

def remove
  u = User.find(1)
  u.foo = false
  u.save
  u.reload
  head :ok
end

React 按钮组件:

...

_add(){
  $.ajax({
    url: ''url-to-the-controller-action-(add),
    type: 'POST',
    success: function (data) {
        console.log("DB is set to: " this.props.uid)
    },
    error: function (data) {
        console.log("not added")
    }
  });
},

_remove(){
  $.ajax({
    url: ''url-to-the-controller-action-(remove),
    type: 'POST',
    success: function (data) {
        console.log("DB is set to: " this.props.uid) 
    },
    error: function (data) {
        console.log("not removed")
    }
  });
},

render(){
  return(
    <div>
      <button onClick={this._add}>add</button>
      <button onClick={this._remove}>remove</button>
    </div>
  )
}

...

我的按钮从另一个组件接收道具:

Foo 组件

getInitialState: function() {
  return{
    uid: this.props.data,

  }
}

Foo 的渲染:

<Button uid={this.state.uid} />

我确信我可以在不需要flux/redux 的情况下实现这一点,因为这对于这个微小的组件来说太过分了。 I have looked into this 但不知道怎么用。

该应用可以运行,但我必须刷新页面才能看到更改。

或者,Rails 5 是我最好的动作电缆选择?

【问题讨论】:

    标签: javascript ruby-on-rails ajax ruby-on-rails-4 reactjs


    【解决方案1】:

    成功后,您需要通知 Foo 组件而不是 uid 已更改。

    在 Foo 组件中:

    onChange: (uid) ->
       this.setState({uid: uid})
    
    render: ->
      <Button uid={this.state.uid} onChange={this.onChange}/>
    

    在Button组件中:

    _add(){
      $.ajax({
        url: ''url-to-the-controller-action-(add),
        type: 'POST',
        success: function (data) {
         this.props.onChange(data["uid"])
         console.log("DB is set to:", data["uid"])
        },
        error: function (data) {
           console.log("not added")
        }
      });
    },
    

    在你的行动中:

    def add
      ...
      render json: { uid: u.foo }
    end
    

    关于为什么需要在此处刷新:

    当您进行 ajax 调用时,数据库中的数据会更新。但是在您的成功回调中,您需要使用新数据更新您的视图。当您记录 this.props.uid 时,会将旧数据记录在内存中,当您点击刷新时,数据会被数据库中的新数据替换。

    例如,在 jQuery 中,您需要将 DOM 中的元素替换为在成功回调中传递的新数据。在 ReactJS 中,您需要更新状态以重新渲染组件。

    这里,您的组件 Button 是 Foo 的子组件,并接收 uid 类似的 props。因此,您需要通知您的父组件 uid 已更改为更新状态,并重新渲染自身及其子组件。

    【讨论】:

    • 好的。今天晚些时候我会去。我会回来报告的。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-12
    • 2021-09-25
    • 2022-07-21
    • 2011-08-26
    • 2018-04-22
    • 2017-04-17
    • 2020-02-07
    相关资源
    最近更新 更多