编程语言
首页 > 编程语言> > javascript – Redux saga没有调用API

javascript – Redux saga没有调用API

作者:互联网

我正在尝试使用redux-saga来调用我的API并将其传递给参数.我正在使用redux-logger和console.log()进行调试.但似乎我的传奇因为某些原因没有调用API.

这是状态的控制台日志……因为你可以看到apiMsg没有改变,但我对每个动作都有所改变.

enter image description here

我认为我在动作,减速器或组件中的某个地方出错了.或者我在Saga中调用API错误.

这是我的代码

api.js

import axios from 'axios';

export function getPostApi(postId){
  return axios.get(
    `https://jsonplaceholder.typicode.com/posts/${postId}`
  ).then(
    response => {
      return response;
    }
  ).catch(
    err => {throw err;}
  );
}

我的商店

import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware from 'redux-saga'
import {createLogger} from 'redux-logger';
import rootReducer from '../Reducers';

export default function configureStore(initialState) {
  const sagaMiddleware = createSagaMiddleware();
  const logger = createLogger();
  return {
    ...createStore(rootReducer, initialState, applyMiddleware(sagaMiddleware, logger)),
    runSaga: sagaMiddleware.run
  }
}

传奇

import {call, put, takeEvery} from 'redux-saga/effects';
import * as service from '../Services/api';
import * as actions from '../Actions';
import * as types from '../actions/actionTypes';

export function* fetchPost(action){
  try{
    yield put(actions.apiRequest());
    const [post] = yield [call(service.getPostApi, action.postId)];
    yield put(actions.apiRequestSucceeded(post));
  } catch(e){
    yield put(actions.apiRequestFailed());
  }
}

export function* watchApiRequest() {
  yield takeEvery(types.FETCH_POST, fetchPost);
}

行动

import * as types from './actionTypes';

export const fetchPost = (postId) => ({
  type: types.FETCH_POST,
  postId,
});

export const apiRequest = () => {
  return {
    type: types.API_REQUEST
  }
}

export const apiRequestSucceeded = (post) => {
  return {
    type: types.API_REQUEST_SUCCEEDED,
    post
  }
}

export const apiRequestFailed = () => {
  return {
    type: types.API_REQUEST_FAILED
  }
}

减速器

import * as types from '../actions/actionTypes';

const initialState = {
  apiMsg: '',
  postId: 1,
  fetching: false,
  post: null
};

export default function getPostData(state = initialState, action) {
  switch (action.type) {
    case types.API_REQUEST:
      return {
        ...state,
        apiMsg: 'API call request!',
        fetching: true
      }
    case types.API_REQUEST_SUCCEEDED:
      return {
        ...state,
        apiMsg: 'API called succeeded!',     
        fetching: false,
        postId: action.post.id,
        post: action.title
      };
    case types.API_REQUEST_FAILED:
      return {
        ...state,
        apiMsg: 'API called failed!',
        fetching: false,
      };
    default:
      return state;
  }
}

组件页面

import React, { Component } from 'react';
import { View, Text} from 'react-native';
import { connect } from 'react-redux';
import {fetchPost} from './Actions/apiTesterActions';

class TestPage extends Component {
  constructor() {
    super();
  }

  componentDidMount() {
    this.props.fetchPost(1)
  }

   render() {
    const { postId, fetching, post } = this.props;
    console.log('Test page props', postId, fetching, post);
    return (
      <View> 
        <Text>Test Page Works! </Text>
      </View>
    )
  }
}

const mapStateToProps = (state) => {
  return {
    postId: state.getPostData.postId,
    fetching: state.getPostData.fetching,
    post: state.getPostData.post
  }
};

export default connect(mapStateToProps, {fetchPost})(TestPage);

我还在学习Redux,现在还有redux-saga,所以我不完全理解结构/层次结构,但我正在学习,任何建议都有帮助.谢谢

编辑:
我使用redux saga api call example作为指南.

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import { Provider } from 'react-redux';
import configureStore from './ReduxTest/Store/configureStore';
import rootSaga from './ReduxTest/sagas';

const store = configureStore();
store.runSaga(rootSaga)

ReactDOM.render(<Provider store={store}><App /></Provider>, document.getElementById('root'));
registerServiceWorker();

佐贺/ index.js

import {fork, all} from 'redux-saga/effects';
import {watchApiRequest} from './apiTester';

export default function* rootSaga() {
  yield all [
    fork(watchApiRequest)
  ]
}

解决方法:

经过一段时间的大量调试后,我发现了问题.

当我第一次开始创建应用程序时,我收到以下错误…

[…effects] has been deprecated in favor of all([…effects]), please update your code

由于所有产品都被弃用了,我改变了我的代码而没有考虑到它,我很高兴错误发生了,但没有意识到它对我的应用程序会产生多大的影响.

(错)saga / index.js

import {fork, all} from 'redux-saga/effects';
import {watchApiRequest} from './apiTester';

export default function* rootSaga() {
  yield all [
    fork(watchApiRequest)
  ]
}

(右)saga / index.js

import {fork, all} from 'redux-saga/effects';
import {watchApiRequest} from './apiTester';

export default function* rootSaga() {
  yield all ([
    fork(watchApiRequest)
  ])
}

你可以看到它需要用括号括起来产生所有([…])
您将收到已弃用的错误,但您的代码仍然有效.我不确定如何修复已弃用的错误.

如果有人知道如何摆脱已弃用的错误而不是那么好.

标签:javascript,reactjs,redux,react-redux,redux-saga
来源: https://codeday.me/bug/20190705/1388184.html