src/Service/Post.js
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/dist/query"
export const postAPi=createApi({
reducerPath:'postApi',
baseQuery:fetchBaseQuery({
baseUrl:"https://jsonplaceholder.typicode.com/",
}),
endpoints:(builder)=>({
getAllPost:builder.query({
query:()=>({
url:'posts',
method:'GET'
})
})
})
})
export const { useGetAllPostQuery }=postAPi
Run Code Online (Sandbox Code Playgroud)
src/App.js
import { useGetAllPostQuery } from './Service/Post'
export default function App() {
const data=useGetAllPostQuery()
return (
<div>
<h1>
React App
</h1>
</div>
)
}
Run Code Online (Sandbox Code Playgroud)
我使用 RTK 查询获取数据,因此,当我尝试在 app.js 反应组件中访问 useGetAllPostQuery 时,它在浏览器中看到错误 TypeError: Object(...) is not a function 所以,任何人都可以建议如何解决此错误
当我们需要通过api获取一些数据并且我们在react中使用redux时,我们使用redux-thunk或saga,但我的问题是也可以通过组件useEffect钩子,我们在useEffect中调用api,然后使用redux存储中的action传递数据。