?? 如果還不了解 HTML 、 CSS和JS,可以參考本號(hào)下的 HTML21 天入門(mén)教程、 CSS 21 天入門(mén)教程和JS21天入門(mén)教程。
在 React 應(yīng)用中實(shí)現(xiàn) AJAX 請(qǐng)求,有以下兩種方式:
- 使用第三方庫(kù)如 axios、JQuery 等。
無(wú)論使用哪一種,基本上實(shí)現(xiàn)的都是副作用,而前面說(shuō)過(guò),副作用使用 useEffect 鉤子來(lái)處理。
一個(gè)例子
假設(shè)現(xiàn)在有一個(gè)獲取 Course 的 API,它返回的數(shù)據(jù)如下:
{ "courses": [ { "id": 1, "name": "HTML入門(mén)", "description": "基礎(chǔ)課程。" }, { "id": 2, "name": "CSS入門(mén)", "description": "基礎(chǔ)課程。" }, { "id": 3, "name": "JavaScript入門(mén)", "description": "基礎(chǔ)課程。" }, ] }
現(xiàn)在需要調(diào)用此 API 獲取提供的數(shù)據(jù),并顯示在頁(yè)面上。
CourseComponent 組件實(shí)現(xiàn)這個(gè)功能。
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 中,通過(guò) fetch 方法調(diào)用 courses 的 API。
這里同時(shí)加上錯(cuò)誤處理,這是好的習(xí)慣。
在 return 里,通過(guò) map 方法遍歷 courses 的值,并通過(guò)列表呈現(xiàn)出來(lái)。
使用 axios 庫(kù)
以上代碼可以使用 axios 庫(kù)來(lái)實(shí)現(xiàn)。
因?yàn)?axios 是第三方庫(kù),使用前需要安裝它。
使用 npm 通過(guò)命令 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 中直接寫(xiě) fetch 請(qǐng)求是一種常見(jiàn)的數(shù)據(jù)獲取方式。
但是這種方法有很多需要手動(dòng)處理的部分,且有明顯的弊端。
因此對(duì)于正式的項(xiàng)目,React 官方首推使用基于 React 的框架,比如說(shuō) next.js,這種框架里內(nèi)置有數(shù)據(jù)獲取方式。
它會(huì)解決直接寫(xiě) fetch 帶來(lái)的比如,效率低,不夠簡(jiǎn)潔之類的弊端。
總結(jié)
最后來(lái)總結(jié)一下今天的內(nèi)容要點(diǎn):
- ?? 在 React 中實(shí)現(xiàn) AJAX 請(qǐng)求可以通過(guò) fetch API 或第三方庫(kù)。
- ?? 在 useEffect 鉤子中處理 AJAX 這樣的副作用。
- ?? 在正式的項(xiàng)目中,不推薦自己處理數(shù)據(jù)請(qǐng)求 fetch,而是推薦使用框架內(nèi)置的數(shù)據(jù)獲取方式。
該文章在 2024/12/9 18:40:16 編輯過(guò)