首页 文章

使用React更新状态

提问于
浏览
0

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

所以在App中,我的getInitialState包含一系列帖子(帖子)和一串输入文本(postbody) . 我使用componentDidMount向我的数据库发出AJAX GET请求,因此用户可以看到所有帖子 .

为了处理输入文本我刚刚创建了一个简单的handleChange函数来更新postbody的状态 .

我还有一个handleClick函数,它抓取this.state.postbody然后POST它数据库 . 但是,相同的函数也会使数据库的单独GET请求更新posts数组的状态 . 这似乎不对!不应该以其他方式处理并自动更新? *这是我的主要问题 . *

另外,如果我需要进一步破坏组件,或者如果我违反了使用React的最佳做法(例如,在错误的地方更改状态,或者使用道具不正确),请告诉我 .

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>
    )
  }
})

1 回答

  • 2

    好吧,实际上因为你只有一个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数据操作到商店中 . 并在商店中添加一个侦听器,以使用状态变量发布React组件的更新并更新它 .

    Whenever something changes in the store, change the state variable from within the store using a listener (在商店,组件和api调用之间来回传递数据)和组件更新 . 这就是Flux的工作原理 . 还有其他方法可以做到这一点 . 刚开始 .

相关问题