Reactjs 反应-在不同组件更改状态时更新组件
我有一个标题组件下拉列表,它的行为就像我整个应用程序的过滤器。假设我的布局中有一个网格组件,其中填充了一些数据,例如某一年可用的汽车列表。当我从标题年份的下拉列表中选择时,我想更新我的网格组件,使其仅包含在所选年份可用的汽车 这是我的减速机,带有用于header组件中下拉菜单的action creator。为了简洁起见,我删除了一些代码Reactjs 反应-在不同组件更改状态时更新组件,reactjs,redux,Reactjs,Redux,我有一个标题组件下拉列表,它的行为就像我整个应用程序的过滤器。假设我的布局中有一个网格组件,其中填充了一些数据,例如某一年可用的汽车列表。当我从标题年份的下拉列表中选择时,我想更新我的网格组件,使其仅包含在所选年份可用的汽车 这是我的减速机,带有用于header组件中下拉菜单的action creator。为了简洁起见,我删除了一些代码 export interface IImporterSelectorContextState { dataQuery?: ServiceApi.IDat
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;
}
当选择year时,调用changeYearContext函数,我的状态设置为header组件的新值。我不知道如何更新显示汽车的网格组件。要根据我的过滤器获取新数据,我必须发送new request got按钮以获取新数据,但我希望在选择new year from dropdown时刷新数据。我如何才能做到这一点?您可以通过两种方式实现: 方法1:最简单的方法是使用select组件的onChange属性绑定事件handler,如下所示:
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和implement request作为更改redux状态的副作用,使用此方法,首先更改年份状态,然后加载数据并将其推送到状态,
我建议您阅读中的文档。我通过使用componentWillReceiveProps功能找到了一个可行的解决方案,在该功能中,我必须检查道具是否已更改,然后采取措施。不知道这是否是正确的解决方案,但它可以按照我的要求工作。componentWillReceiveProps现在已被弃用,并被静态方法getDerivedStateFromProps取代。请看componentWillReceiveProps或getDerivedStateFromProps不是触发副作用的好地方,它的目的是更新状态,通过比较,您应该使用componentDidUpdate来解决您的副作用,比如ajax callsGood to know,所以我将其移动到componentDidUpdate生命周期方法。谢谢