?? 如果還不了解 HTML 、 CSS和JS,可以參考本號下的 HTML21 天入門教程、 CSS 21 天入門教程和JS21天入門教程。
在 React 應(yīng)用中實現(xiàn) AJAX 請求,有以下兩種方式:
無論使用哪一種,基本上實現(xiàn)的都是副作用,而前面說過,副作用使用 useEffect 鉤子來處理。
一個例子
假設(shè)現(xiàn)在有一個獲取 Course 的 API,它返回的數(shù)據(jù)如下:
{ "courses": [ { "id": 1, "name": "HTML入門", "description": "基礎(chǔ)課程。" }, { "id": 2, "name": "CSS入門", "description": "基礎(chǔ)課程。" }, { "id": 3, "name": "JavaScript入門", "description": "基礎(chǔ)課程。" }, ] }
現(xiàn)在需要調(diào)用此 API 獲取提供的數(shù)據(jù),并顯示在頁面上。
CourseComponent 組件實現(xiàn)這個功能。
function CourseComponent() { const [error, setError] = useState(null); const [isLoaded, setIsLoaded] = useState(false); const [courses, setCourses] = useState([]); useEffect(() => { fetch("https://api.xxx.com/courses") //返回上述JSON格式的數(shù)據(jù)。 .then(res => res.json()) .then( (result) => { setIsLoaded(true); setCourses(result); }, (error) => { setIsLoaded(true); setError(error); } ) }, []) if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return ( <div> <ul> {courses.map(course => ( <li key={course.id}> {course.name}: {course.description} </li> ))} </ul> </div> ); } }
上述代碼中的 useEffect 中,通過 fetch 方法調(diào)用 courses 的 API。
這里同時加上錯誤處理,這是好的習慣。
在 return 里,通過 map 方法遍歷 courses 的值,并通過列表呈現(xiàn)出來。
使用 axios 庫
以上代碼可以使用 axios 庫來實現(xiàn)。
因為 axios 是第三方庫,使用前需要安裝它。
使用 npm 通過命令 npm install axios
安裝。
然后,在組件代碼中引入它。
import axios from 'axios'; function CourseComponent() { const [error, setError] = useState(null); const [isLoaded, setIsLoaded] = useState(false); const [courses, setCourses] = useState([]); useEffect(() => { axios.get("https://api.xxx.com/courses") //返回上述JSON格式的數(shù)據(jù)。 .then(res => res.json()) .then( (result) => { setIsLoaded(true); setCourses(result); }, (error) => { setIsLoaded(true); setError(error); } ) }, []) if (error) { return <div>Error: {error.message}</div>; } else if (!isLoaded) { return <div>Loading...</div>; } else { return ( <div> <ul> {courses.map(course => ( <li key={course.id}> {course.name}: {course.description} </li> ))} </ul> </div> ); } }
以上這種在 Effect 中直接寫 fetch 請求是一種常見的數(shù)據(jù)獲取方式。
但是這種方法有很多需要手動處理的部分,且有明顯的弊端。
因此對于正式的項目,React 官方首推使用基于 React 的框架,比如說 next.js,這種框架里內(nèi)置有數(shù)據(jù)獲取方式。
它會解決直接寫 fetch 帶來的比如,效率低,不夠簡潔之類的弊端。
總結(jié)
最后來總結(jié)一下今天的內(nèi)容要點:
- ?? 在 React 中實現(xiàn) AJAX 請求可以通過 fetch API 或第三方庫。
- ?? 在 useEffect 鉤子中處理 AJAX 這樣的副作用。
- ?? 在正式的項目中,不推薦自己處理數(shù)據(jù)請求 fetch,而是推薦使用框架內(nèi)置的數(shù)據(jù)獲取方式。
該文章在 2024/12/9 18:40:16 編輯過