在看到他使用一些在線 api 提供服務后,我觀看了一個教程,了解 redux 工具包是如何作業的
這是我的 store.js
import {configureStore} from '@reduxjs/toolkit'
import {setupListeners} from '@reduxjs/toolkit/query'
import { postApi } from './actions/productAction'
export const store = configureStore({
reducer:{
[postApi.reducerPath]:postApi.reducer
},
// middleware:(getDefaultMiddleware)=>getDefaultMiddleware().concat(postApi.middleware),
// middleware is also created for us, which will allow us to take advantage of caching, invalidation, polling, and the other features of RTK Query.
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware().concat(postApi.middleware),
})
setupListeners(store.dispatch)
這里我有一個動作檔案,它實際上正在更新動作狀態
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'
export const postApi = createApi({
reducerPath:'postApi',//this is unique path which will tell the broweser where it need to store the cookie data
baseQuery: fetchBaseQuery({
baseUrl:'',
}),
endpoints:(builder)=>({
getAllPost: builder.query({
query:()=>({
url:'http://localhost:5000/api/v1/products',
method:'GET'
})
}),
getPostById: builder.query({
query: (id) =>({
url:`posts/${id}`,
method:'GET'
})
})
})
})
export const {useGetAllPostQuery,useGetPostByIdQuery} = postApi
我呼叫這個函式的地方是
import React from 'react'
import {useGetAllPostQuery} from '../../actions/productAction'
// import Card from '../../components/Card';
const HomePage = () => {
console.log(useGetAllPostQuery())
const responseInfo = useGetAllPostQuery()
console.log("the response i am getting is",responseInfo)
return (
<>
<h1>Hello worls</h1>
</>
)
}
export default HomePage
我得到的控制臺我不知道為什么會出現這個錯誤請求在我的郵遞員作業的同時被拒絕

錯誤擴展影像

實際問題是

uj5u.com熱心網友回復:
看起來它沒有得到 URL 嘗試像這樣添加你的基本 URL
export const postApi = createApi({
reducerPath:'postApi',
baseQuery: fetchBaseQuery({
baseUrl:'http://localhost:5000/', //added your base url
}),
endpoints:(builder)=>({
getAllPost: builder.query({
query:()=>({
url:'api/v1/products' // this should take only one argument
})
}),
getPostById: builder.query({
query: (id) =>({
url:`posts/${id}` // this should take only one argument
})
})
})
})
更多詳情,可以參考這里rtk 查詢
uj5u.com熱心網友回復:
兄弟,我也看了那個教程,太舊了。這是獲取的正確方法。如果這個答案對您有幫助,請告訴我。而且您還可以自動完成匯入。如果您按照該教程進行操作,則您沒有從正確的位置匯入。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import React from 'react'
import {useGetAllPostQuery} from '../../actions/productAction'
// import Card from '../../components/Card';
const HomePage = () => {
console.log(useGetAllPostQuery())
//You can also desctructure it like this {data:responseInfo}, you must not directly change the value.
const {data} = useGetAllPostQuery()
return (
<>
//Then you check if data exist first because the initial value is empty. you can also check like this <div>{data?.map((my data)=> <>...</>))}</div>
<div>{data && data.map((mydata, i)=> (
//You can tag on what you want to display. if you want to display names, then you can say madata.name
<p key={i}>{mydata}</p>
))}</div>
</>
)
}
export default HomePage
要解決 cors 錯誤,請嘗試以下操作:
在根檔案夾下創建 vercel.json。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
{
"headers": [
{
"source": "/api/(.*)",
"headers": [
{ "key": "Access-Control-Allow-Credentials", "value": "true" },
{ "key": "Access-Control-Allow-Origin", "value": "*" }, // Change this to specific domain for better security
{
"key": "Access-Control-Allow-Methods",
"value": "GET,OPTIONS,PATCH,DELETE,POST,PUT"
},
{
"key": "Access-Control-Allow-Headers",
"value": "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version"
}
]
}
]
}
轉到 /api/index.js 檔案。
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
export default async (req, res) => {
const { method } = req;
// This will allow OPTIONS request
if (method === "OPTIONS") {
return res.status(200).send("ok");
}
};
uj5u.com熱心網友回復:
我沒有正確查看控制臺,主要問題是后端不允許我查詢 api,這很奇怪我沒有使用 axios 找到這意味著我不需要使用 cors 來使用 axios 訪問 api 但如果你正在這樣做使用 redux 工具包那么你需要使用 cors
npm install cors
然后將這些行添加到您的主后端檔案中
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors());
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/432994.html
標籤:javascript 反应 反应还原 redux 工具包
