React Redux API轮询每x秒

13

我已经让它运作起来了,但我想找一种更好的做法。

它使用https://icanhazdadjoke API来显示每 x 秒更新的随机笑话。有没有更好的方法?

最终,我想添加停止、开始、重置功能,感觉这种方式可能不是最好的。

有没有可以使用的中间件?

Redux 操作。

// action types
import axios from 'axios';
export const FETCH_JOKE = 'FETCH_JOKE';
export const FETCH_JOKE_SUCCESS = 'FETCH_JOKE_SUCCESS';
export const FETCH_JOKE_FAILURE = 'FETCH_JOKE_FAILURE';


function fetchJoke() {
  return {
    type: FETCH_JOKE
  };
}

function fetchJokeSuccess(data) {
  return {
    type: FETCH_JOKE_SUCCESS,
    data
  };
}

function fetchJokeFail(error) {
  return {
    type: FETCH_JOKE_FAILURE,
    error
  };
}

export function fetchJokeCall(){
  return function(dispatch){
    dispatch(fetchJoke());
    return axios.get('https://icanhazdadjoke.com', { headers: { 'Accept': 'application/json' }})
    .then(function(result){
      dispatch(fetchJokeSuccess(result.data))
    })
    .catch(error => dispatch(fetchJokeFail(error)));
  }
}

Redux 的 reducer

import {combineReducers} from 'redux';
import {FETCH_JOKE, FETCH_JOKE_SUCCESS, FETCH_JOKE_FAILURE} from '../actions';

const defaultStateList = {
  isFetching: false,
  items:[],
  error:{}
};

const joke = (state = defaultStateList, action) => {
  switch (action.type){
  case FETCH_JOKE:
    return {...state, isFetching:true};
  case FETCH_JOKE_SUCCESS:
    return {...state, isFetching:false, items:action.data};
  case FETCH_JOKE_FAILURE:
    return {...state, isFetching:false, error:action.data};
  default:
    return state;
  }
};

const rootReducer = combineReducers({
  joke
});

export default rootReducer;

笑话组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { fetchJokeCall } from '../actions';


class Joke extends Component {
  componentDidMount() {
    this.timer = setInterval(()=>  this.props.fetchJokeCall(), 1000);
  }
  componentWillUnmount() {
    clearInterval(this.timer)
    this.timer = null;
  }
  render() {
    return (
      <div>
        {this.props.joke.joke}
      </div>
    );
  }
}

Joke.propTypes = {
  fetchJokeCall: PropTypes.func,
  joke: PropTypes.array.isRequired
};

function mapStateToProps(state) {
  return {
    joke: state.joke.items,
    isfetching: state.joke.isFetching
  };
}

export default connect(mapStateToProps, { fetchJokeCall })(Joke);

你可以尝试使用Thunk中间件,通过调度你的fetch结果并使用你的actions应用于你的状态。这是一个非常小的库,被广泛使用。 - Xorifelse
他似乎已经在使用redux thunk了。我建议你查看Nir Kaufman关于编写自己的中间件的书籍。所有这些副作用在中间件中都非常好。 - mattdevio
5个回答

14

Redux-Sagas更好,我们也在应用程序中使用它,以下是您如何使用Redux-Sagas进行轮询:

为了让您有一个想法,以下是您可以执行的操作,您还需要了解Redux-Sagas的工作原理

Action

export const FETCH_JOKE = 'FETCH_JOKE';
export const FETCH_JOKE_SUCCESS = 'FETCH_JOKE_SUCCESS';
export const FETCH_JOKE_FAILURE = 'FETCH_JOKE_FAILURE';
export const START_POLLING = 'START_POLLING';
export const STOP_POLLING = 'STOP_POLLING';

function startPolling() {
      return {
        type: START_POLLING
      };
    }

function stopPolling() {
      return {
        type: STOP_POLLING
      };
    }

function fetchJoke() {
  return {
    type: FETCH_JOKE
  };
}

function fetchJokeSuccess(data) {
  return {
    type: FETCH_JOKE_SUCCESS,
    data
  };
}

function fetchJokeFail(error) {
  return {
    type: FETCH_JOKE_FAILURE,
    error
  };
}

Reducer

import {combineReducers} from 'redux';
import {FETCH_JOKE, FETCH_JOKE_SUCCESS, FETCH_JOKE_FAILURE, START_POLLING, STOP_POLLING } from '../actions';

const defaultStateList = {
  isFetching: false,
  items:[],
  error:{},
  isPolling: false,
};

const joke = (state = defaultStateList, action) => {
  switch (action.type){
  case FETCH_JOKE:
    return {...state, isFetching:true};
  case FETCH_JOKE_SUCCESS:
    return {...state, isFetching:false, items:action.data};
  case FETCH_JOKE_FAILURE:
    return {...state, isFetching:false, error:action.data};
  case START_POLLING:
    return {...state, isPolling: true};
  case STOP_POLLING:
    return {...state, isPolling: false};
  default:
    return state;
  }
};

const rootReducer = combineReducers({
  joke
});

export default rootReducer;

传说

import { call, put, takeEvery, takeLatest, take, race } from 'redux-saga/effects'

import {FETCH_JOKE, FETCH_JOKE_SUCCESS, FETCH_JOKE_FAILURE, START_POLLING, STOP_POLLING } from '../actions';

import axios from 'axios';



function delay(duration) {
  const promise = new Promise(resolve => {
    setTimeout(() => resolve(true), duration)
  })
  return promise
}

function* fetchJokes(action) {
  while (true) {
    try {
      const { data } = yield call(() => axios({ url: ENDPOINT }))
      yield put({ type: FETCH_JOKE_SUCCESS, data: data })
      yield call(delay, 5000)
    } catch (e) {
      yield put({ type: FETCH_JOKE_FAILURE, message: e.message })
    }
  }
}

function* watchPollJokesSaga() {
  while (true) {
    const data = yield take(START_POLLING)
    yield race([call(fetchJokes, data), take(STOP_POLLING)])
  }
}

export default function* root() {
  yield [watchPollJokesSaga()]
}

如果你想深入了解,还可以使用Redux-Observable,阅读这篇文章


更新了答案。 - Haider Ali
1
@Adam,你实现了这个吗?我认为这就是答案,因为你想使用redux来实现轮询。 - Haider Ali
'payloadIfAny'未定义,'dataIfAny'未定义。同时,在watch中您正在定义数据但从未使用过它。 - Adam
1
谢谢,我今天做了类似的事情。我可以确认你的例子是有效的,这将对帮助他人非常有用。但现在我已经让它工作了,我在考虑WebSockets可能是一个更好、更现代的解决方案。你有什么想法吗? - Adam
1
是的,你说得对。我也使用了WebSocket,而且不需要轮询,因为可以实现监听器和回调函数。但我认为仅将WebSocket用于获取API数据并不是我想要做的事情。我会将WebSocket用于实时聊天或视频通话等实时操作。 - Haider Ali
显示剩余9条评论

1
我已经做了一个小的(5kb gzipped)助手来创建基于redux-thunk store的轮询。这个想法是有一个逻辑来防止重复注册相同的轮询,有迭代之间的回调等等。

https://www.npmjs.com/package/redux-polling-thunk


1

我一直在解决类似的问题,但我并不关心如何启动和停止轮询。由于某种原因,while循环会导致我的应用程序冻结,因此我放弃了它,并改为像这样设置我的saga。

import { all, takeLatest, call, put } from 'redux-saga/effects';
import axios from 'axios';

import { API_CALL_REQUEST, API_CALL_SUCCESS, API_CALL_FAILURE, API_CALL_FETCHED } from 
'../actions/giphy';

function apiFetch() {
  let randomWord = require('random-words');
  let API_ENDPOINT = `https://api.giphy.com/v1/gifs/search? 
                   api_key=MYKEY&q=${randomWord()}&limit=12`;
  return axios({
    method: "get",
    url: API_ENDPOINT
 });
}

export function* fetchImages() {
  try {
   const res = yield call(apiFetch)
   const images = yield res.data
   yield put({type: API_CALL_SUCCESS, images})

} catch (e) {
  yield put({type: API_CALL_FAILURE, e})
  console.log('Error fetching giphy data')
 }
}

export default function* giphySaga() {
  yield all([
    takeLatest(API_CALL_REQUEST, fetchImages),
 ]);
}    

然后在我的组件内部添加了这个。
 componentDidMount() {
   this.interval = setInterval(() => {
   this.props.dispatch({type: 'API_CALL_REQUEST'});
   }, 5000);
  }

componentWillUnmount() {
  clearInterval(this.interval)
}

它可以运行,但希望能得到一些反馈,看看如何可能改进。


1
这是一种简单的方法,虽然不是最优解,但不需要额外使用任何库。

操作

// action types
import axios from 'axios';

export const START_POLLING_JOKE = 'START_POLLING_JOKE';
export const STOP_POLLING_JOKE = 'STOP_POLLING_JOKE';
export const FETCH_JOKE = 'FETCH_JOKE';
export const FETCH_JOKE_SUCCESS = 'FETCH_JOKE_SUCCESS';
export const FETCH_JOKE_FAILURE = 'FETCH_JOKE_FAILURE';

const defaultPollingInterval = 60000

function startPollingJoke(interval = defaultPollingInterval) {
  return function (dispatch) {
    const fetch = () => dispatch(fetchJoke())
    dispatch({
      type: START_POLLING_JOKE,
      interval,
      fetch,
    })
  }
}

function stopPollingJoke() {
  return {
    type: STOP_POLLING_JOKE
  }
}

function fetchJoke() {
  return {
    type: FETCH_JOKE
  };
}

function fetchJokeSuccess(data) {
  return {
    type: FETCH_JOKE_SUCCESS,
    data
  };
}

function fetchJokeFail(error) {
  return {
    type: FETCH_JOKE_FAILURE,
    error
  };
}

export function pollJokeCall(interval = defaultPollingInterval) {
  return function (dispatch) {
    dispatch(fetchJoke())
    dispatch(startPollingJoke(interval))
  }
}

export function fetchJokeCall() {
  return function(dispatch){
    dispatch(fetchJoke());
    return axios.get('https://icanhazdadjoke.com', { headers: { 'Accept': 'application/json' }})
    .then(function(result){
      dispatch(fetchJokeSuccess(result.data))
    })
    .catch(error => dispatch(fetchJokeFail(error)));
  }
}

Reducers
import {combineReducers} from 'redux';
import {
  START_POLLING_JOKE,
  STOP_POLLING_JOKE,
  FETCH_JOKE, 
  FETCH_JOKE_SUCCESS, 
  FETCH_JOKE_FAILURE,
} from '../actions';

const defaultStateList = {
  isFetching: false,
  items:[],
  error:{},
  pollingId: null,
  polling: false,
};

const joke = (state = defaultStateList, action) => {
  switch (action.type){
  case START_POLLING_JOKE: 
    clearInterval(state.pollingId)
    return {
      ...state,
      polling: true,
      pollingId: setInterval(action.fetch, action.interval),
    }
  }
  case STOP_POLLING_JOKE: 
    clearInterval(state.pollingId)
    return {...state, polling: false, pollingId: null}
  case FETCH_JOKE:
    return {...state, isFetching:true};
  case FETCH_JOKE_SUCCESS:
    return {...state, isFetching:false, items:action.data};
  case FETCH_JOKE_FAILURE:
    return {...state, isFetching:false, error:action.data};
  default:
    return state;
  }
};

const rootReducer = combineReducers({
  joke
});

export default rootReducer;

组件(可能存在错误,因为我不习惯类组件)

import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { pollJokeCall, stopPollingJoke } from '../actions';


class Joke extends Component {
  componentDidMount() {
    this.props.pollJokeCall()
  }
  componentWillUnmount() {
    this.props.stopPollingJoke()
  }
  render() {
    return (
      <div>
        {this.props.joke.joke}
      </div>
    );
  }
}

Joke.propTypes = {
  pollJokeCall: PropTypes.func,
  stopPollingJoke: PropTypes.func,
  joke: PropTypes.array.isRequired,
};

function mapStateToProps(state) {
  return {
    joke: state.joke.items,
    isfetching: state.joke.isFetching
  };
}

export default connect(mapStateToProps, { pollJokeCall, stopPollingJoke })(Joke);

0

redux-saga非常棒,我一直在与redux一起使用它。它提供了一个很好的API,可以执行延迟、轮询、节流、竞态条件和任务取消等操作。因此,使用redux-saga,您可以添加一个观察器来保持轮询。

function* pollSagaWorker(action) {
  while (true) {
    try {
      const { data } = yield call(() => axios({ url: ENDPOINT }));
      yield put(getDataSuccessAction(data));
      yield call(delay, 4000);
    } catch (err) {
      yield put(getDataFailureAction(err));
    }
  }
}


1
那个 while (true) 循环必要吗?看起来像是我想避免的东西。 - Xorifelse
谢谢。我已经在我的示例上进行了改进,使用了一个不同的API来填充表格。使用redux-saga,这样做是否会防止每次刷新整个表格?另外,使用WebSockets呢?这种方式对性能有好处吗? - Adam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接