【问题标题】:React - update component when different component changed stateReact - 当不同组件更改状态时更新组件
【发布时间】:2018-06-10 20:16:24
【问题描述】:

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

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

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

When year is selected, changeYearContext function is called, my state is set to new values for header component.我不确切知道如何更新显示汽车的网格组件。要根据我的过滤器获取新数据,我必须发送新请求(获取按钮)以获取新数据,但我想在选择下拉菜单时刷新数据。我怎样才能做到这一点?

【问题讨论】:

    标签: reactjs redux


    【解决方案1】:

    您可以通过两种方式实现:

    方法1:最简单的,使用你的select组件的onChange属性绑定一个事件处理函数,像这样:

    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,实现request作为改变redux状态的副作用,用这个方法,首先你改变年份状态,然后,你的数据被加载并推送到状态, 我建议你阅读来自https://github.com/redux-saga/redux-saga的文档

    【讨论】:

    • 我通过使用componentWillReceiveProps 函数找到了一个可行的解决方案,我必须检查道具是否已更改然后执行某些操作。不知道它是否是正确的解决方案,但它可以按我的意愿工作。
    • componentWillReceiveProps 现在已被弃用并被静态方法 getDerivedStateFromProps 取代 请参阅hackernoon.com/… componentWillReceiveProps 或 getDerivedStateFromProps 不是触发副作用的好地方,它的目的是更新状态,您应该使用 componentDidUpdate 代替您的身边通过比较像 ajax 调用的效果
    • 很高兴知道,所以我把它移到了 componentDidUpdate 生命周期方法。谢谢
    猜你喜欢
    • 2019-06-13
    • 2021-08-11
    • 2018-09-21
    • 2016-09-23
    • 2018-10-09
    • 2019-12-29
    • 1970-01-01
    • 2020-07-18
    • 2021-06-08
    相关资源
    最近更新 更多