如何从服务器响应创建更新React表

问题描述 投票:1回答:1

目的是通过服务器响应创建表。

响应代码(它给出一个数组):

function Parse() {
  var store;
  var request = 'http://localhost:3001/Products?city=0&shop=0';
  axios.get(request)
    .then(function(response) { 
      store = response.data; 
      return store;  //        <--- Q1
    })
    .catch(function (error) {
      () => { cl("Server Error: ", error) };
    });
 }

现在我需要创建一个表:

class ProductsTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      store: []
    };
  }

  render() {
    // this.setState({store:Parse()})  //<---  Q2
    return (
      <div className='ProductsTable'>
        <p>{this.state.store}</p>
      </div>
    );
  }
};

Q1-返回商店(项目数组)

Q2-不能使用setState,因为它会产生循环。

需要向服务器发出请求并更新表的Button:

class LeftPanel extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      store: []
    };
  }

  render() {
    var funct = function(elem) {
      <ProductsTable />
    }
    return (
      <div className='PanelContent Center'>
        <CreateButtons funct={funct} />
      </div>
    );
  }
};

class CreateButtons extends React.Component {
  render() {
    var rows = [];
    rows.push(<TheButton source={source} funct={this.props.funct}/>);
    return(<div className='MenuTable Center'>{rows}</div>);
  }
};

class TheButton extends React.Component {
  render() {
    elem = <button onClick={this.props.funct}></button>;
    return <div>{elem}</div>;
  }
};

但我不知道如何在一个工作环境中实现它。我应该在哪里放置setState,如何更新?谢谢。

我在搜索中发现了很多关于它的信息,但是我无法在我的项目中使用它 - 我对React结构没有足够的了解。

javascript json reactjs response
1个回答
0
投票

试试这个:

首先制作ProductsTableTheButton哑组件(无状态)。将Parse()保留为辅助函数,但将其重命名为fetchData()

function fetchData() {
  return axios.get('http://localhost:3001/Products?city=0&shop=0')
    .then(response => response.data); 
    .catch((err) => { cl("Server Error: ", err); throw err; });
}

class ProductsTable extends React.Component {
  render() {
    return (
      <div className='ProductsTable'>
        <p>{this.props.products}</p>
      </div>
    );
  }
};

class TheButton extends React.Component {
  render() {
    return (
      <div>
        <button onClick={this.props.onClick} />
      </div>
    );
  }
};

然后将控制逻辑放在父对象LeftPanel中。

class LeftPanel extends React.Component {
  constructor(props) {
    super(props);
    this.getData = this.getData.bind(this);
    this.state = { store: [] };
  }

  getData() {
    fetchData().then((data) => this.setState({ store: data }));
  }

  render() {
    return (
      <div className='PanelContent Center'>
        <div className='MenuTable Center'>
          <TheButton onClick={this.getData} />
        </div>
        <ProductsTable products={this.state.store} />
      </div>
    );
  }
};

您可能需要更改一些细节以满足您的特定需求。

© www.soinside.com 2019 - 2024. All rights reserved.