如何应用加载更多按钮在React中推送this.state

时间:2018-03-06 00:10:57

标签: javascript reactjs ecmascript-6 jsx fetch-api

实现Schema::create('despesas', function (Blueprint $table) { $table->increments('id_despesa'); $table->integer('categoria')->unsigned(); $table->string('descricao'); $table->Integer('valor_previsto'); $table->Integer('valor_real'); $table->timestamps(); }); Schema::create('categorias', function (Blueprint $table) { $table->increments('id'); $table->string('nome'); $table->timestamps(); }); Schema::table('despesas', function (Blueprint $table) { $table->foreign('categoria')->references('id')->on('categorias'); }); 按钮的目的是通过API获取更多对象并在不刷新页面的情况下显示。仍不确定实现setState方法的方法是否理想

<a className="button" onClick={this.loadMore}>Load more news</a>

App.js

this.setState({
  newsData: [...this.state.newsData, ...responseJson]
}) 

Newslist.js

import React from 'react';
import { Newslist } from './newslist/Newslist';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      page: 1,
      newsData: ''
    }
  }
  componentDidMount() {
    this.page = 1;
    this.requestNews();
  }

  requestNews () {
    console.log('koooy');
    fetch('http://localhost:3000/api/?page='+this.page)
    .then((response) => response.json())
    .then((responseJson) => {
        this.setState({
          newsData: [...this.state.newsData, ...responseJson]
        })
    })
    .catch((error) => {
      console.error(error);
    });
  }

  loadMore = () => {
    this.requestNews();
  }

  render() {
    return (
      <main className="main">
        <h1>Hello mate !</h1>
        <Paggination />
        { this.state.newsData.length
          ? <Newslist currentNews={this.state.newsData} loadMoreData={this.loadMore} />
          : <p>Loading...</p>
        }
      </main>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:1)

你所做的似乎是合理的。基本上,请确保您知道您当前的新闻页面/偏移量。当您发出API请求时,请使用请求发送页面/偏移量,并将新用法附加到数组的头部或尾部。

我注意到有关使用Redux的建议,Redux相当复杂,这是一个非常简单的问题,在这里不需要它。