React - 在不同组件更改状态

时间:2018-06-10 20:16:24

标签: reactjs redux

我在标题组件下拉列表中的行为类似于整个我的应用程序的过滤器。假设我的布局中有网格组件,其中包含一些数据,例如某些年份可用的汽车列表。当我从标题年份的下拉列表中选择时,我想更新我的网格组件以仅包含选定年份中可用的汽车。

这是我的reducer,带有动作创建器,用于标题组件中的下拉列表。为简洁起见,我删除了一些代码。

export interface IImporterSelectorContextState {
    dataQuery?: ServiceApi.IDataQuery;
    data?: any[];
    context?: ServiceApi.IDocumentContext
}    
type KnownAction = 
    IChangeCurrentContext

export const actionCreators = {
    changeYearContext: (context: ServiceApi.IDocumentContext) : AppThunkAction<KnownAction> => (dispatch, getState) => {
        dispatch(changeCurrentContext(context));
    }
}

const unloadedState: IImporterSelectorContextState = {
   //removed for brevity
};

export const reducer: Reducer<IImporterSelectorContextState> = (state: IImporterSelectorContextState,
    incomingAction: Action) => {

    const action = incomingAction as KnownAction;
    switch (action.type) {
        case CHANGE_CURRENT_CONTEXT:
            return {
                ...state,
                context: action.context
            }
        default:
            const exhaustiveCheck: never = action;
    }
    return state || unloadedState;
}

选择年份时,将调用changeYearContext函数,我的状态将设置为标题组件的新值。我不确切知道如何更新显示汽车的网格组件。要根据我的过滤器获取新数据,我必须发送新请求(获取该按钮)以获取新数据,但我想在选择下拉列表的新年时刷新数据。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:1)

您可以通过两种方式实现这一目标:

方法1:最简单的,使用select组件的onChange属性绑定事件hanlder,如下所示:

import {Component} from 'react'
class MyHeaderComponent extends Component{
  render(){
    return (
      <select onChange={(e)=>this.changeYearHandler(e.target.value)}>
        <option></option>
        ...
      </select>
    )
  }
  changeYearHandler(value){
    fetch(MY_API_URI, /* and pass value with post json or other way*/).then(data=>{
      // give it to redux via prop bound with react-redux's connect method
      this.props.changeYearContext(data)
    })
  }
}

方法2:使用redux-saga并实现请求作为更改redux状态的副作用,使用此方法,首先,更改年份状态,然后,将数据加载并推送到状态, 我建议你阅读https://github.com/redux-saga/redux-saga

中的文档
相关问题