试图理解Redux-Saga的React。所面临的问题是在尝试调用API时。尽管配置了API,但是应用程序使用它自己的本地calendar.js文件中存在的相同静态数据。
我正在尝试使用API,而不是使用静态硬编码数据。
api_helper.js
import axios from "axios"
import accessToken from "./jwt-token-access/accessToken"
const token = accessToken
//url to get data is : https://jsonplaceholder.typicode.com/users
const API_URL = "https://jsonplaceholder.typicode.com/"
const axiosApi = axios.create({
baseURL: API_URL,
})
axiosApi.defaults.headers.common["Authorization"] = token
axiosApi.interceptors.response.use(
response => response,
error => Promise.reject(error)
)
export async function get(url, config = {}) {
//the following does not work
// return await axiosApi.get(`users`, { ...config }).then(response => response.data)
return await axiosApi.get(url, { ...config }).then(response => response.data)
}url_helper.js
export const GET_EVENTS = "/events"backend_helper.js
import axios from "axios"
import { del, get, post, put } from "./api_helper"
import * as url from "./url_helper"
//Tried export const getEvents = () => get('/users')
export const getEvents = () => get(url.GET_EVENTS)saga.js,则console.log(响应)将导致calendar.js文件中存在静态内容。
import {
getEvents
} from "helpers/backend_helper"
function* fetchEvents() {
try {
const response = yield call(getEvents)
console.log(response)
yield put(getEventsSuccess(response))
} catch (error) {
yield put(getEventsFail(error))
}
}
function* calendarSaga() {
yield takeEvery(GET_EVENTS, fetchEvents)
}API这里面临的问题是调度方法不能调用index.js,而是从calendar.js获取静态内容。
import {
getEvents
} from "../../store/actions"
const Calender = props => {
const { events, categories } = props
useEffect(() => {
const { onGetEvents } = props
onGetEvents()
}, [])
const mapStateToProps = ({ calendar }) => ({
events: calendar.events,
categories: calendar.categories,
})
const mapDispatchToProps = dispatch => ({
onGetEvents: () => dispatch(getEvents())
})
export default connect(mapStateToProps, mapDispatchToProps)(Calender)actions.js
import {
GET_EVENTS
} from "./actionTypes";
export const getEvents = () => ({
type: GET_EVENTS,
});calendar.js
const events = [
{
id: 1,
title: "Hey!",
start: new Date().setDate(new Date().getDate() + 1),
className: "bg-warning text-white",
},
...
]发布于 2021-08-14 09:33:13
您的调度操作错误。您可能需要调度redux操作。所以为了让redux-saga监听你的行为。您可以尝试以下操作:
const mapDispatchToProps = (dispatch) => ({
onGetEvents: () =>
dispatch({
type: GET_EVENTS,
}),
});https://stackoverflow.com/questions/68781926
复制相似问题