1

我认为我的代码是正确的,它会检查 QueryString 是否未定义。如果是,则“thePath”从配置文件中获取值。如果 QueryString 有一个值(这意味着不再未定义),那么让 't​​hePath' 的值是 QueryString。它可以工作,但它不会在函数的 return(dispatch) 部分中更新.. 为什么?

该函数用于根据 axios 的结果设置不同的操作,最终成为 reducer 和 redux store 的一部分。

export let fetchingBook = (QueryString) => {

    let thePath;
    if (QueryString === undefined) {
        thePath = process.env.REACT_APP_GATEWAY_BOOK_PATH
    }
    else
        if (QueryString !== undefined) {
            thePath = QueryString
    }
    
    console.log("thePath : " + thePath);

    return (dispatch) => {

        console.log("came to return dispatch first time, does not come here the second time.. why?");

        dispatch(fetch_BOOK_Request())

        axios.get(thePath)
            .then(response => {
                const BookDATA = response.data
                dispatch(fetch_BOOK_Success(BookDATA))
            })
            .catch(error => {
                const ErrorMsg = error.message
                dispatch(fetch_BOOK_Failure(ErrorMsg))
            })
    }
}

更新:它在哪里被派出

const dispatching = dispatch => {
    return {
      // following is for another reducer
      goFindByPlanNumber__functionalProp: planNum => dispatch({ type: "SEARCH_BY_PLAN_NUMBER", txt: planNum }, fetchingBook(planNum)),
       //calling or dispatching fetchingBook here. it was added in the component using import
      fetchingBook__functionalProp:(planNum)=> dispatch(fetchingBook(planNum))
  
    }
  
  }
4

1 回答 1

2

这是一个如何使用 redux thunk 执行异步操作的基本示例(我制作的中间件的行为类似于 thunk)

const { Provider, connect } = ReactRedux;
const { createStore, applyMiddleware } = Redux;
const defaultState = { val: 0 };
const store = createStore(
  (state = defaultState, action) => {
    //reducer
    if (action.type === 'OK') {
      return {
        ...state,
        val: state.val + 1,
      };
    }
    if (action.type === 'DATA') {
      return {
        ...state,
        data: action.payload,
      };
    }
    return state;
  },
  defaultState,
  //somple redux thunk like middleware
  applyMiddleware(store => next => action => {
    if (typeof action === 'function') {
      return action(store.dispatch, store.getState);
    }
    return next(action);
  })
);
class App extends React.Component {
  state = { selectedId: 0 };
  render() {
    return (
      <div>
        <div>
          <button onClick={this.props.action}>
            {this.props.val}
          </button>
        </div>
        <div>
          <select
            value={this.state.selectedId}
            onChange={e => {
              this.setState({ selectedId: e.target.value });
              this.props.getData(e.target.value);
            }}
          >
            <option value={0}>select id</option>
            {[1, 2, 3, 4, 5].map(id => (
              <option key={id} value={id}>
                {id}
              </option>
            ))}
          </select>
        </div>
        <div>
          data is:{' '}
          {JSON.stringify(this.props.data, undefined, 2)}
        </div>
      </div>
    );
  }
}
const ConnectedApp = connect(
  state => ({ val: state.val, data: state.data }), //map state to props
  {
    //map dispatch to props
    action: () => (dispatch, getState) => {
      //thunk like action
      console.log(
        'in action, current state is',
        getState()
      );
      dispatch({ type: 'OK' });
      let timesExecuted = 0;
      const timer = setInterval(() => {
        timesExecuted++;
        dispatch({ type: 'OK' });
        if (timesExecuted > 3) {
          clearInterval(timer);
        }
      }, 1000);
    },
    getData: id => dispatch => {//get data action
      //you can dispatch loading action
      fetch(
        `https://jsonplaceholder.typicode.com/todos/${id}`
      )
        .then(response => response.json())
        .then(data =>
          dispatch({ type: 'DATA', payload: data })
        );
    },
  }
)(App);
ReactDOM.render(
  <Provider store={store}>
    <ConnectedApp />
  </Provider>,
  document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>

<div id="root"></div>

于 2020-03-20T21:12:45.367 回答