簡體   English   中英

無需任何中間件即可在Redux中處理異步操作

[英]Handling async actions in Redux without any middleware

我正在嘗試異步操作,並嘗試在不使用任何中間件的情況下處理異步操作。 這是代碼:

import React, { Component } from 'react';
import { render } from 'react-dom';
import { createStore, combineReducers } from 'redux';
import { connect, Provider } from 'react-redux';
import './style.css';

const countReducer = (state = { count: 0}, action) => {
  switch (action.type) {
    case 'INC': return { count: state.count + 1 };
    case 'DEC': return { count: state.count - 1 };
    default: return state;
  }
}

const reducers = combineReducers({
  counter: countReducer,
})

const actions = {
  inc: (async () => {
  return await new Promise(resolve => {
    setTimeout(() => {
      resolve({ type: 'INC' });
    }, 200)}
  );
})(),
  dec: () => ({ type: 'DEC' }),
};

const store = createStore(reducers);

class App extends Component {
  render() {
    console.log(this.props, actions);
    return (
      <div>
        <button onClick={this.props.inc}>Increment</button>
        <button onClick={this.props.dec}>Decrement</button>
        <div>Value: {this.props.count}</div>
      </div>
    );
  }
}

const mapStateToProps = ({ counter }) => {
  return { count: counter.count };
}

const AppContainer = connect(mapStateToProps, actions)(App);

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

您可以在此處運行以上代碼。 這不能按預期方式工作。 單擊“減量”將值減1,但單擊“增量”則無任何作用。 上面的代碼有什么問題,我該如何解決? 甚至無需使用像redux-thunk這樣的中間件就可以處理異步操作嗎?

https://reactjs.org/docs/faq-state.html ,告訴我們對setState的調用是異步的,並且在調用setState之后,我們不能立即依賴this.state來反映新值。 這是一種強迫您使用setTimeout 如果不使用Redux,則可以在我提供的鏈接中找到該問題的解決方案。 但是在您使用redux的情況下,您會在https://github.com/reduxjs/redux-thunk#why-do-i-need-this中找到:

Thunk是基本Redux副作用邏輯的推薦中間件,其中包括需要訪問存儲的復雜同步邏輯以及諸如AJAX請求之類的簡單異步邏輯。

這是一個計數器的示例https://github.com/reduxjs/redux/tree/master/examples/counter ,但是您最終將要處理對API和其他異步請求的調用,因此我個人建議您使用thunk因為它是針對與您類似的情況而設計的,所以它為您提供了更好,更優化,更快和更清潔的解決方案,因此您無需自行尋找解決方法。 我希望這是有幫助的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM