【问题标题】:Updating state with React使用 React 更新状态
【发布时间】:2015-11-19 23:16:33
【问题描述】:

我正在使用 React、MongoDB、Express 和 Node 创建博客。我有三个组件:App、List 和 Item。该项目是一篇博客文章;该列表是博客文章的列表,该应用程序包含一个输入文本并提交的地方。我最终会添加更多功能,但我想确定我是否遵守 React 的最佳实践(我怀疑我是)。

所以在 App 中,我使用一组帖子 (posts) 和一个输入文本字符串 (postbody) 来获取初始状态。我使用 componentDidMount 向我的数据库发出 AJAX GET 请求,因此用户可以看到所有帖子。

为了处理输入的文本,我只是做了一个简单的 handleChange 函数来更新 postbody 的状态。

我还有一个 handleClick 函数,它获取 this.state.postbody 然后将其发布到数据库中。然而,相同的函数也会对数据库发出单独的 GET 请求以更新帖子数组的状态。这似乎不对!不应该以其他方式处理并自动更新吗? * 这是我的主要问题。 *

另外,如果我需要进一步分解组件,或者我是否违反了使用 React 的最佳实践(例如,在错误的位置更改状态,或不正确地使用 props),请告诉我。

var React = require('react');

var Item = React.createClass({
  render: function() {
    return (
      <div>
        <h2>{this.props.postbody}</h2>
      </div>
    )
  }
})

var List = React.createClass({

  render: function() {
    return (
      <div>
        {this.props.array.map(function(post) {

          return (
            <Item postbody={post.postbody}></Item>
          )
        })}
      </div>
    )
  }
})

var App = React.createClass({

  getInitialState: function() {
    return {
       posts: [],
       postbody: ''
    }
  },

  componentDidMount: function() {
    $.ajax({
      type: 'GET',
      url: '/api/blogPosts',
      success: function(data) {
        this.setState({posts: data});
      }.bind(this)
    })
  },

  handleClick: function() {

    event.preventDefault();

    var blogPost = this.state.postbody;

    $.ajax({

      type: 'POST',
      url: '/api/blogPosts',
      data: { postbody: blogPost }
    });

    $.ajax({
      type: 'GET',
      url: '/api/blogPosts',
      success: function(data) {
        this.setState({posts: data});
      }.bind(this)
    })
  },

  handleChange: function(event) {

    this.setState({ postbody: event.target.value})
  },

  render: function() {
    return (
      <div>
        <form action="/api/blogPosts" method="post">
            <input onChange={this.handleChange} type="text" name="postbody"></input>
            <button type="button" onClick={this.handleClick}>Submit</button>
        </form>
        <List array={this.state.posts} />
      </div>
    )
  }
})

【问题讨论】:

  • “React 最佳实践”取决于您遵循的数据模式。你看过 Flux 或 Redux 吗?

标签: ajax mongodb reactjs


【解决方案1】:

好吧,实际上,因为您只有一个 Add api 调用,所以您可以这样做。您只需将 blogPost 推送到帖子请求中的帖子数组。此外,您可能希望使用表单的 onSubmit。

var React = require('react');

var Item = React.createClass({
  render: function() {
    return (
      <div>
        <h2>{this.props.postbody}</h2>
      </div>
    )
  }
})

var List = React.createClass({

  render: function() {
    return (
      <div>
        {this.props.array.map(function(post) {

          return (
            <Item postbody={post.postbody}></Item>
          )
        })}
      </div>
    )
  }
})

var App = React.createClass({

  getInitialState: function() {
    return {
       posts: [],
       postbody: ''
    }
  },

  componentDidMount: function() {
    $.ajax({
      type: 'GET',
      url: '/api/blogPosts',
      success: function(data) {
        this.setState({posts: data});
      }.bind(this)
    })
  },

  handleSubmit: function() {

    event.preventDefault();

    var blogPost = this.state.postbody;

    $.ajax({

      type: 'POST',
      url: '/api/blogPosts',
      data: { postbody: blogPost },
      success:function(){
          this.setState({posts: Object.assign([],this.state.posts.push({postbody:postbody}))});  
      }.bind(this)
    });

  },

  handleChange: function(event) {

    this.setState({ postbody: event.target.value})
  },

  render: function() {
    return (
      <div>
        <form action="/api/blogPosts" method="post" onSubmit={this.handleSubmit}>
            <input onChange={this.handleChange} type="text" name="postbody"></input>
            <input type="submit" value="Submit" >Submit</button>
        </form>
        <List array={this.state.posts} />
      </div>
    )
  }
})

这个想法是您维护一个存在于组件之外的商店,并通过各种事件/操作来管理商店。在这种情况下,应用程序相对简单,因此我们可以将“商店”作为状态道具并通过 POST XHR 进行更改。

但是,随着您的应用逻辑不断增加,将帖子数据存储在商店中。并将动作 CRUD 数据放入存储中。并在 store 上添加一个监听器来发布对 React 组件的更新并使用状态变量对其进行更新。

每当 store 发生变化时,使用监听器从 store 中更改 state 变量(在 store、组件和 api 调用之间来回传递数据)并更新您的组件。这就是 Flux 的工作原理。还有其他方法可以做到这一点。只是一个开始。

【讨论】:

    猜你喜欢
    • 2016-03-10
    • 2020-06-19
    • 2021-03-16
    • 2020-04-14
    • 2020-10-19
    • 2019-10-17
    • 2016-11-10
    • 2020-03-08
    • 1970-01-01
    相关资源
    最近更新 更多