设置redux thunk的麻烦

时间:2018-03-21 18:16:05

标签: redux axios redux-thunk

我有以下动作创建者:

export function selectBook(ISBN, dispatch) {
    const url = `${ROOT_ITEMS_URL}/${ISBN}?all=true`;
    dispatch({ type: 'SELECT_BOOK_LOADING', isLoading:true });
    axios.get(url)
        .then(({ data }) => dispatch({ type: 'SELECT_BOOK_SUCCESS', data}))
        .catch(( err ) => dispatch({ type: 'SELECT_BOOK_FAILURE', isLoading:false}))
}

我的项目主索引文件中也有以下内容:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';

import LoginLayout from './layouts/LoginLayout';

import reducers from './reducers';
import ReduxPromise from 'redux-promise';
import reduxThunk from 'redux-thunk';

const createStoreWithMiddleware = applyMiddleware(ReduxPromise, reduxThunk)(createStore);
//const createStoreWithMiddleware = applyMiddleware()(createStore);

ReactDOM.render(
    <Provider store={createStoreWithMiddleware(reducers)}>
        <LoginLayout />
    </Provider>
    , document.querySelector('.root'));

我很困惑如何调用调用到我的项目中。我收到以下错误:

  

bundle.js:5690 Uncaught TypeError:dispatch不是函数

当我调用此函数时,我没有通过任何调度。但我不知道如何调用它。这是我需要用函数调用进行的redux调用吗?

this.props.selectBook(params.bookID);

应该是这样吗?:

this.props.selectBook(params.bookID, dispatch);

和什么导入派遣?来自&#39; redux&#39;?

的导入调度

2 个答案:

答案 0 :(得分:1)

尝试像这样做你的动作创作者: <br.com.sapereaude.maskedEditText.MaskedEditText android:id="@+id/phone_input" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="phone" android:typeface="monospace" mask:allowed_chars="1234567890" mask:mask="##:###" android:hint="12:34" app:keep_hint="true" /> 它需要返回功能

答案 1 :(得分:1)

dispatch通过redux-thunk免费提供给您。这里的诀窍是你的动作创建者应该返回一个函数,函数的第一个参数将是dispatch。您的动作创建者最终会看起来像这样:

export function selectBook(ISBN) {
  return dispatch => {
    const url = `${ROOT_ITEMS_URL}/${ISBN}?all=true`;
    dispatch({ type: 'SELECT_BOOK_LOADING', isLoading:true });
    axios.get(url)
      .then(({ data }) => dispatch({ type: 'SELECT_BOOK_SUCCESS', data}))
      .catch(( err ) => dispatch({ type: 'SELECT_BOOK_FAILURE', isLoading:false}))
  }
}
相关问题