我是个初学者,对redux和redux-saga感到不舒服。我在一个传奇文件中进行API调用。但是在我收到呼叫响应之前,操作已调度。
rootSaga.js
import {all} from 'redux-saga/effects';
import {watchAll} from './todoSaga';
export default function* rootSaga(){
yield all([
watchAll()
])
}
todoSaga.js
import {put, takeLatest, call, all} from 'redux-saga/effects';
import axios from 'axios';
import {ADD_TODO, GET_TODO, ADD_TODO_SUCCESS,GET_TODO_SUCCESS, DELETE_TODO_SUCCESS,DELETE_TODO,UPDATE_TODO,UPDATE_TODO_SUCCESS} from '../Actions/actionTypes';
const BaseUrl = "http://localhost:8002/api";
export function* getTodoSaga(){
try{
const response = yield call(axios.get, (`${BaseUrl}/todos`) )
yield put({type:GET_TODO_SUCCESS,payload:response.data})
}
catch(e){
console.log(e)
}
}
export function* addTodoSaga(action){
try{
const response = yield call(axios.post, (`${BaseUrl}/addtodo`),action.payload )
yield put({type:ADD_TODO_SUCCESS, payload:response.data})
}
catch(e){
console.log(e)
}
}
export function* deleteTodoSaga(action){
try{
const response = yield call(axios.delete,(`${BaseUrl}/delete/${action.payload}`))
yield put({type:DELETE_TODO_SUCCESS, payload:response.data})
}
catch(e){
console.log(e)
}
}
export function* updateTodoSaga(action){
try{
const response = yield call(axios.put,(`${BaseUrl}/update/${action.payload.id}`),action.payload.todo)
yield put({type:UPDATE_TODO_SUCCESS, payload:response.data})
}
catch(e){
console.log(e)
}
}
export function* watchAll(){
yield all([
takeLatest(GET_TODO,getTodoSaga),
takeLatest(DELETE_TODO,deleteTodoSaga),
takeLatest(ADD_TODO,addTodoSaga),
takeLatest(UPDATE_TODO,updateTodoSaga)
]);
}
actionTypes.js
export const ADD_TODO = "ADD_TODO"
export const DELETE_TODO = "DELETE_TODO"
export const UPDATE_TODO = "UPDATE_TODO"
export const GET_TODO = "GET_TODO"
export const ADD_TODO_SUCCESS = "ADD_TODO_SUCCESS"
export const DELETE_TODO_SUCCESS = "DELETE_TODO_SUCCESS"
export const UPDATE_TODO_SUCCESS = "UPDATE_TODO_SUCCESS"
export const GET_TODO_SUCCESS = "GET_TODO_SUCCESS"
export const UPDATE_STATUS_TODO = "UPDATE_STATUS_TODO"
export const UPDATE_STATUS_TODO_SUCCESS = "UPDATE_STATUS_TODO_SUCCESS"
actionCreators.js
import {ADD_TODO,GET_TODO, DELETE_TODO, UPDATE_TODO,UPDATE_STATUS_TODO} from './actionTypes'
export const getToDo =() =>{
return{
type: GET_TODO
}
}
export const addToDo = (todo) =>{
return{
type: ADD_TODO,
payload: todo
}
}
export const deleteToDo = (id) =>{
return{
type: DELETE_TODO,
payload: id
}
}
export const updateToDo = (id,todo) =>{
return{
type: UPDATE_TODO,
payload: {id,todo}
}
}
export const updateStatusToDo = (id,completed) =>{
return{
type: UPDATE_STATUS_TODO,
payload:{id,completed}
}
}
我仅在updateTodoSaga函数中面临问题。
yield put({type:UPDATE_TODO_SUCCESS, payload:response.data})
在从API调用获得响应之前被调用。另外,我尝试推迟,但我认为有更好的方法可以做到。 我想念什么吗?