【问题标题】:React and Redux dispatch function problemsReact 和 Redux dispatch 函数问题
【发布时间】:2021-04-27 16:14:47
【问题描述】:

我想了解 React、Redux 和 Axios 是如何协同工作的,但我碰壁了,我需要一些帮助...... 我的问题是动作内部有一个调度,但是在我返回调度之后它不会继续。 我很可能不明白这是如何工作的,所以请尝试尽可能详细地解释。提前致谢。

我的 combineReducer

import {combineReducers} from "redux";
import getAvailableDatesReducer from "./getAvailableDatesReducer";

export default combineReducers({
    availableDates: getAvailableDatesReducer
});

我的减速器

import {FETCH_AVAILABLE_DATES} from "../actions/types";

const initialState = {
    availableDates: null
};

const getAvailableDatesReducer = (state = initialState, action) => {
    switch (action.type) {

        case FETCH_AVAILABLE_DATES:
            return {...state, availableDates: action.availableDates};

        default:
            console.log('just default..');
            return state;
    }
}

export default getAvailableDatesReducer;

我的行动

export const fetchAvailableDates = (appointmentKey) => {
    //return (dispatch) => {
        axios.post('/app_dev.php/termin/getavailability/new', {
            appointmentKey: appointmentKey
        }).then((response) => {
            console.log('response received...');
            return (dispatch) => {
                console.log('not hitting this...');
                dispatch({type: FETCH_AVAILABLE_DATES, availableDates: response.data.availability});
            };
        }).catch(err => {
            console.log(err);
        });

    //}
}

我的组件

import {fetchAvailableDates} from "../actions";

const Calendar = (props, appointmentKey) => {

    useEffect(() => {
            fetchAvailableDates(appointmentKey);
    }, []);

    const mapStateToProps = (state) => {
        return {
            availableDates: state.availableDates,
    }
}

export default connect(mapStateToProps, {fetchAvailableDates})(Calendar);

我的 index.js 文件

import {Provider} from 'react-redux';
import thunk from 'redux-thunk';
import {applyMiddleware, compose, createStore} from "redux";
import reducers from './reducers';

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducers, composeEnhancers(applyMiddleware(thunk)));

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

【问题讨论】:

    标签: reactjs redux axios


    【解决方案1】:
    • 首先,在你的动作文件中创建一个动作:

      const fetchDatesAction = (response) => ({
        type: FETCH_AVAILABLE_DATES,
        availableDates: response.data.availability,
      });
      
    • 那么,更新connect

      export default connect(mapStateToProps, {fetchDatesAction})(Calendar);
      
    • 最后在useEffect调用api,如下:

      useEffect(() => {
        axios
          .post("/app_dev.php/termin/getavailability/new", {
            appointmentKey: appointmentKey,
          })
          .then((response) => {
            console.log("response received...");
            return (dispatch) => {
              console.log("not hitting this...");
              props.fetchDatesAction();
            };
          })
          .catch((err) => {
            console.log(err);
          });
      }, []);
      

    【讨论】:

    • 嗨,我定义了 fetchAction。 axios 调用是在 action 内部还是必须在 useEffect 内部有关系吗?
    【解决方案2】:

    Thunk 是一个库,负责处理 redux 状态管理中的副作用。 Redux 是一个简单的纯函数,它接受状态和动作作为输入,并基于这两者返回一个新状态。所以它非常简单直接。 现在,在某些情况下,例如您在示例中提到的情况,我们需要执行一些异步操作,这些操作可能不会立即提供结果,而是提供承诺。在这种情况下,我们需要使用第三方工具,也称为enhancer。 这就是你添加的原因

    const store = createStore(reducers, composeEnhancers(applyMiddleware(thunk)));
    

    现在,当触发异步操作时,它会进入 thunk。 Thunk 处理请求,然后触发另一个动作,该动作再次进入减速器。 现在 reducer 是一个纯函数,不区分这些事件源,只是根据动作及其负载更新状态。

    希望这张图能帮助您理解这个概念。 https://miro.medium.com/max/1400/1*QERgzuzphdQz4e0fNs1CFQ.gif

    【讨论】:

      猜你喜欢
      • 2018-07-04
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 2021-10-02
      • 1970-01-01
      • 2020-07-22
      • 2018-08-13
      • 2017-10-31
      相关资源
      最近更新 更多