簡體   English   中英

Redux:異步操作創建者未被調用

[英]Redux: Asynchronous action creator not being called

我正在使用redux-thunk創建異步操作,以便可以使用“ fetch”調用API方法。 我已經將我的redux存儲附加到了我的根App組件,如下所示:

import React, { Component } from 'react';
import {Provider} from 'react-redux';
import Grid from '../src/Components/Grid/Grid';
import rootReducer from './Reducer';
import './App.css';
import { createStore,applyMiddleware } from 'redux';
import ReduxThunk from 'redux-thunk';
import logger from 'redux-logger';

class App extends Component {
  render() {
    return (
      <Provider  store={createStore(rootReducer,{},applyMiddleware(ReduxThunk))}>
      <div className="App">
            <Grid></Grid>
      </div>
      </Provider>
    );
  }
}

export default App;

我已經定義了我的異步動作創建者,如下所示:

import config from 'react-global-configuration';
import fetch from 'cross-fetch';

export default function textChangeActionCreator(data){
    console.log('in action createor'+data)

    return  async function(dispatch){
        console.log('fetching....')
         return await fetch(data).
         then((data)=>{ 
             console.log(data);
             dispatch({type:'text_change',payload:data}) 
            }).
         catch((err)=>{console.log(err)})
        }
}

我的問題是,當我從任何組件調用上述動作創建者時,它都會被正確調用,但是第二個console.log('fetching....')沒有出現,並且fetch()調用似乎沒有發生。

我究竟做錯了什么?

更新

這是調用動作創建者的組件代碼:

class Grid extends React.PureComponent{

constructor(props)
{
    super(props);
    this.state={dynamicButtonText:'',seachText:''}
    this.updateDynamicText=this.updateDynamicText.bind(this);      
    this.onTextChanged=this.onTextChanged.bind(this);
    this.updateSearchText=this.updateSearchText.bind(this);
}

onTextChanged()
{
    textChangeActionCreator(searchURL);
}

 render()
  {....}
}
const mapStateToProps=(state)=>{return state;}

export default connect(mapStateToProps,{textChangeActionCreator})(Grid);

這通常是由錯誤的操作調用引起的。 請確保你你都調用textChangeActionCreator()行動的創建者,並通過結果來dispatch()propsToDispatch對象傳遞給connect()

export default connect(mapStateToProps, dispatch => {

    /* Call textChangeActionCreator() and pass the result to dispatch() */
    return {
         textChange : (data) => dispatch(textChangeActionCreator(data))
    }
})(YourComponent);

更新

只是查看您的代碼,似乎您是直接從onTextChanged()調用動作創建者。 您需要通過組件的props調用它,如下所示:

onTextChanged()
{
    this.props.textChangeActionCreator(searchURL);
}

嘗試這樣的事情:

const textChangeActionCreator = (data) => {
  console.log(`in action createor ${data}`);

  return (dispatch) => {
    console.log('fetching...');
    return fetch(data)
      .then((data)=>{ 
        console.log(data);
        dispatch({ type:'text_change', payload:data });
      })
      .catch((err)=>{ console.log(err); });
  };
};

您不需要等待或異步,因為您正在返回一個Promise,因此應在調用此函數的地方等待。

另外,您在這里使用currying,因此您必須調用類似的東西:const fetchedData = await textChangeActionCreator(data)(dispatch);

暫無
暫無

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

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