获取获取响应,并添加到应用程序而不刷新

时间:2016-11-30 22:14:55

标签: javascript reactjs

我通过PUT提取添加一个项目,我看到它的唯一方法就是刷新页面(它来自一个获取GET)。

但是,我希望立即添加。我希望它将API的响应添加到州。

我尝试用

做这件事

.then((res) => res.json()).then((item) => this.props.addItem(item))

然后尝试使用我的主要组件渲染它但没有成功。我没有错误。

<PhotoGalleryLevel {...props} addItem={(item) => this.setState({ tags: [item].concat(this.state.tags)})}>

我把所有code in a codepen here

这是我进行抓取的地方:

var PhotoGalleryLevel = React.createClass({
  getDefaultProps: function(){
    return {
      level: 1
    }
  },
    handleSubmit1: function(e, value) {
    e.preventDefault();
     return fetch('localhost:8000/createapi', {
     method: 'POST',
     body: JSON.stringify({
      'name':this.state.tagname,
      'taglevel':this.props.level}
      )
      })
      .then((res) => res.json()).then((item) => this.props.addItem(item))
      .catch((err) => console.error(err))
  },
  onChange(e) { 
    this.setState({[e.target.name]: e.target.value})
  },
  displayChildren: function () {
    const { children } = this.props;
    return React.Children.map(children, function(child) {
      if(child.type.displayName == this.constructor.displayName) {
        return React.cloneElement(child, {
          ...this.props,
          children: child.props.children,
          level: this.props.level+1,
        });
      }
      return child;
    }.bind(this));
  },
  render: function () {
    var getCategoriesForLevel = this.props.displayedCategories.some(function (tag) {
      return tag.taglevel === this.props.level;
    }.bind(this));
    var filteredTags = this.props.tags.filter(function (tag) {
      return tag.taglevel === this.props.level;
    }.bind(this));
    return (
              <div>
        <div className="filter-panel">
           <form onSubmit={this.handleSubmit1}>
              <input name="tagname" type="text" placeholder={'Add L' + this.props.level} onChange={this.onChange} />
            </form>
          {filteredTags.map(function (tag, index){
            return <PhotoGalleryButton buttonElement={'a'} className={'test1'} key={index} tag={tag} selectTag={this.props.selectTag} />;
          }.bind(this))}
        </div>
        {this.displayChildren()}
     </div>
    );
  }
});

1 个答案:

答案 0 :(得分:0)

我可能错了,但我的想法是从状态渲染它,如下所示:

var PhotoGalleryLevel = React.createClass({
  getInitialState: function() {
    var tags = this.props.tags.filter(function (tag) {
      return tag.taglevel === this.props.level;
    }.bind(this));

    return {
      tags: tags
    };
  },
  getDefaultProps: function(){
    return {
      level: 1
    }
  },
  handleSubmit1: function(e, value) {
    e.preventDefault();
    return fetch('localhost:8000/createapi', {
      method: 'POST',
      body: JSON.stringify({
        'name':this.state.tagname,
        'taglevel':this.props.level
      })
    })
      .then((res) => res.json())
      .then((item) => this.setState({ tags: [item].concat(this.state.tags)}))
      .catch((err) => console.error(err))
  },
  onChange(e) { 
    this.setState({[e.target.name]: e.target.value})
  },
  displayChildren: function () {
    const { children } = this.props;
    return React.Children.map(children, function(child) {
      if(child.type.displayName == this.constructor.displayName) {
        return React.cloneElement(child, {
          ...this.props,
          children: child.props.children,
          level: this.props.level+1,
        });
      }
      return child;
    }.bind(this));
  },
  render: function () {
    // let className
    // let buttonElement
    var getCategoriesForLevel = this.props.displayedCategories.some(function (tag) {
      return tag.taglevel === this.props.level;
    }.bind(this));
// switch(this.props.level) {
    return (
              <div>
        <div className="filter-panel">
                          <form onSubmit={this.handleSubmit1}>
                    <input name="tagname" type="text" placeholder={'Add L' + this.props.level} onChange={this.onChange} />
                </form>
          {this.state.tags.map(function (tag, index){
            return <PhotoGalleryButton buttonElement={'a'} className={'test1'} key={index} tag={tag} selectTag={this.props.selectTag} />;
          }.bind(this))}
        </div>
        {this.displayChildren()}
     </div>
    );
  }
});

但请记住:

这是一种不好的做法 - &#34;使用道具在getInitialState中生成状态通常会导致真实来源的重复,即真实数据的位置。&#34; - http://reactjs.cn/react/tips/props-in-getInitialState-as-anti-pattern.html