我如何将数据从API移动到状态钩



我已经多次遇到了这个问题,我可以使用一些建议。我有一个API电话。我想在另一个是表格的孩子的组件中显示结果。我已经制定了一个可以将状态映射到JSX的组件,但是我很难理解我从API响应中实际使用新数组的部分。我的功能可以从单独的模块中进行此调用。

const data = []  
const search = (values, loadData) => {
fetch(`/search`, {
    method: 'POST',
    headers: headers,
    body: values
})
    .then(checkStatus)
    .then(parseJSON)
    .then(res => {
               let items = res.response.docs
                for (let i = 0; i < items.length; i++) {
                    console.log(items[i].start)
                    data.push({
                        headline: items[i].title,
                        web_url: items[i].web_url,
                        snippet: items[i].snippet
                    })
                }
                console.log(data)
            }
          )
}
const fetcher ={search, otherthings}
export default fetcher

我想拥有一组可以使事物模块化的方法,但是在将API响应映射到状态时,我有点朦胧。

在您想做这样的表单的孩子中显示结果,其中搜索结果设置为" component"状态并传递给显示它们的组件。<<<<<<<<<</p>

我已经简化了请求函数以删除大量代码,该代码只会更改文档列表的单个属性名称并为示例模拟。

import React, { useState } from "react";
// our search function which will return a promise that resolves to docs
const search = values =>
  // fetch(`/search`, {
  //   method: 'POST',
  //   headers: headers,
  //   body: values
  // })
  //   .then(checkStatus)
  //   .then(parseJSON)
  //   .then(res => res.response.docs);
  Promise.resolve([{ id: 1, name: "doc 1" }, { id: 2, name: "doc 2" }])
// our component to render the results
const Results = ({ docs }) => docs.map(doc => <div key={doc.id}>{doc.name}</div>);
// our Search component with the form that passes results to it's child
const Search = () => {
  const [results, setResults] = useState([]);
  // call setResults with the value returned by `search`
  const doSearch = e => search({ query: e.currentTarget.value }).then(setResults);
  return (
    <div>
      <form>
        <input onChange={doSearch} />
      </form>
      <div>
        <Results docs={results} />
      </div>
    </div>
  )
}

请参阅此处的工作示例.. https://codesandbox.io/s/5zrx67k94

只需在输入中键入一个字符即可触发请求。

中显示结果,您想使用中央数据存储(例如Redux)或使用React Context的任何其他组件。对于后者,您可以将持有结果的状态移动,然后将搜索功能转移到上下文组件中,并导出功能和结果,将其从您的表单中使用以进行呼叫并设置状态,并将其从其他组件中使用访问状态。您还需要在两个组件上方的组件树中渲染上下文提供商。

也许现在从上面的简单解决方案开始。

最新更新