React:在路线变更时没有开火

时间:2016-05-03 05:58:25

标签: javascript reactjs redux react-redux

我有几条使用相同控制器的路线:

class Something
  attr_reader :my_something

  def initialize
    @my_something = []
  end

  def dosomething
    s = 5
    @my_something << s
  end
end

something = Something.new
something.my_something
# => []
something.dosomething
# => [5]
something.my_something
# => [5]

当路线改变时,我从组件中调用api函数:

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

这是一个如下行动:

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)
            );
        });
    };
}

在初始页面加载时,它可以工作并从api返回数据并呈现内容。但是,在更改路由时,会触发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 }); }); }; } 函数,但loadSearch(返回实际数据)不会。

1 个答案:

答案 0 :(得分:2)

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

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

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