使用 AJAX 请求获取数据
React 没有规定特定的数据获取方法,但人们通常使用浏览器提供的库,如 axios 或 fetch()
API。
¥React doesn't prescribe a specific approach to data fetching, but people commonly use either a library like axios or the fetch()
API provided by the browser.
全局 fetch
函数允许你发出 AJAX 请求。它接受一个 URL 作为输入并返回一个解析为 Response
对象的 Promise
。你可以找到有关 fetch
此处 的更多信息。
¥The global fetch
function allows you to make AJAX requests. It takes in a URL as an input and returns a Promise
that resolves to a Response
object. You can find more information about fetch
here.
Promise 表示异步操作的最终结果,你可以找到有关 Promises 此处 和 此处 的更多信息。axios 和 fetch()
都在底层使用 Promises。你还可以使用 async / await
语法来减少回调嵌套。
¥A Promise represents the eventual result of an asynchronous operation, you can find more information about Promises here and here. Both axios and fetch()
use Promises under the hood. You can also use the async / await
syntax to reduce the callback nesting.
确保 fetch()
API 和 Promise 在目标受众的浏览器中可用。例如,Internet Explorer 中的支持需要 polyfill。
¥Make sure the fetch()
API and Promises are available in your target audience's browsers.
For example, support in Internet Explorer requires a polyfill.
你可以在 React 网站上的 FAQ 条目 中了解有关从 React 组件发出 AJAX 请求的更多信息。
¥You can learn more about making AJAX requests from React components in the FAQ entry on the React website.