react:调度不触发路由更改

IT技术 javascript reactjs redux react-redux
2021-05-14 05:16:17

我有几个使用相同控制器的路由:

<Route component={Search} path='/accommodation(/:state)(/:region)(/:area)' />

当路由改变时,我从组件内部调用 api 函数:

componentWillReceiveProps = (nextProps) => {
    if (this.props.params != nextProps.params) {
        loadSearch(nextProps.params);
    }
}

这是一个如下的动作:

export function loadSearch (params) {
    return (dispatch) => {
        return dispatch(
            loadDestination(params)
        ).then(() => {
            return dispatch(
                loadProperties(params)
            );
        });
    };
}

其中加载:

export const DESTINATION_REQUEST = 'DESTINATION_REQUEST';
export const DESTINATION_SUCCESS = 'DESTINATION_SUCCESS';
export const DESTINATION_FAILURE = 'DESTINATION_FAILURE';

export function loadDestination (params) {
    const state = params.state ? `/${params.state}` : '';
    const region = params.region ? `/${params.region}` : '';
    const area = params.area ? `/${params.area}` : '';

    return (dispatch) => {
        return api('location', {url: `/accommodation${state}${region}${area}`}).then((response) => {
            const destination = formatDestinationData(response);

            dispatch({
                type: DESTINATION_SUCCESS,
                destination
            });
        });
    };
 }

export const PROPERTIES_REQUEST = 'PROPERTIES_REQUEST';
export const PROPERTIES_SUCCESS = 'PROPERTIES_SUCCESS';
export const PROPERTIES_FAILURE = 'PROPERTIES_FAILURE';

export function loadProperties (params, query, rows = 24) {
    return (dispatch, getState) => {

        const locationId = getState().destination.id || 99996;

        return api('search', {locationId, rows}).then((response) => {
            const properties = response.results.map(formatPropertiesData);

            dispatch({
                type: PROPERTIES_SUCCESS,
                properties
            });
        });
    };
 }

在初始页面加载时,这会起作用并从 api 返回数据并呈现内容。但是,在更改路线时,loadSearch会触发函数,但不会触发 dispatch(返回实际数据)。

1个回答

请将您的代码更改为此。你错过了一个dispatch.

假设:您正在使用 redux-thunk,并且该组件可以通过 props (connected) 访问调度。既然你提到你是在页面加载时调度,我认为是这种情况。

componentWillReceiveProps = (nextProps) => {
   const {dispatch} = this.props;
   if (this.props.params != nextProps.params) {
      nextProps.dispatch(loadSearch(nextProps.params));
   }
}