【问题标题】:Trying to combine an API request with a grid rendering尝试将 API 请求与网格渲染相结合
【发布时间】:2017-11-23 15:22:02
【问题描述】:

所以我已经为 API 请求和网格渲染编写了两块代码,但是我对如何在反应环境中将两者结合起来感到困惑。有什么建议吗?

(这是使用 react-axios)

<Request
      method="get", /* get, delete, head, post, put and patch - required */
      url="http://coincap.io/front", /*  url endpoint to be requested - required */
      debounce={50} /* minimum time between requests events - optional */
      onSuccess={(response)=>{}} /* called on success of axios request - optional */
      onError=(error)=>{} /* called on error of axios request - optional */
    />

我希望删除这些硬编码数据,并使用从对 CoinCap.io 的 api 调用中提取的数据来渲染网格

// Grid data as an array of arrays
const list = [
  ['Brian Vaughn', 'Software Engineer', 'San Jose', 'CA', 95125 /* ... */ ]
  // And so on...
];

function cellRenderer ({ columnIndex, key, rowIndex, style }) {
  return (
    <div
      key={key}
      style={style}
    >
      {list[rowIndex][columnIndex]}
    </div>
  )  
}

ReactDOM.render(
  <Grid
    cellRenderer={cellRenderer}
    columnCount={list[0].length}
    columnWidth={150}
    height={300}
    rowCount={list.length}
    rowHeight={60}
    width={700}
  />,
  document.getElementById('root')
);

【问题讨论】:

    标签: react-virtualized


    【解决方案1】:

    您可以将 API 调用的结果插入到组件的状态中。在您的请求组件中,试试这个: onSuccess={(response)=&gt; this.setState({ list: response });。您也可以考虑在 componentWillMount 这样的组件生命周期方法中进行 API 调用,而不是在 Axios 组件中。

    然后在您的渲染方法中,将您对本地占位符list 的引用替换为this.state.list。显然,您需要对其进行调整以使其在您的组件结构中工作,但如果没有看到完整的组件,这至少应该让您朝着正确的方向前进。

    【讨论】:

    • 太棒了,谢谢唐尼。我已经看到了生命周期方法,但对它们了解不多,所以我会进一步研究,我很感激提醒。
    • Donny,在生命周期方法中调用 API 会是什么样子?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-26
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 2015-06-01
    • 2019-08-14
    • 1970-01-01
    相关资源
    最近更新 更多