我正在使用react-redux,并向我的redux状态添加了一个“过滤器”字段,其中包含我想要用于从数据库接收数据的所有过滤器。
我的目标是在添加过滤器后立即使用更新的过滤器从数据库接收数据。这是我到目前为止得到的:
--- actions.js ---
...
export function addFilter(filter, value) {
return {
type: 'ADD_FILTER',
filter: filter,
value: value
}
}
...
--- reducer.js ---
...
case 'ADD_FILTER':
return update(state, {
filters: {
$merge: {
[action.filter]: action.value
}
}
});
...
---filteringComponent.js ---
...
addFilterAndUpdateData(filter, value) {
this.props.addFilter(filter, value);
this.props.getData(this.props.filters);
// this.props.filters is connected to state.filters.
// it DOES update, but not right away. so when getData is dispatched
// this.props.filters holds the old object and not the updated one
}
...
添加过滤器后,我想立即调度 getData 操作,以便从数据库接收具有最新过滤器的数据。
问题是this.props.filters尚未更新。 有没有办法“等待”更新?
到目前为止,我想出的最好的解决方案是使用 componentWillReceiveProps,但随后我必须添加条件(因为我不一定要在每次 props 更改时分派(dispatch) getData,只有当它是过滤器的结果时)更新)
这里正确的“react-redux”方法是什么?
最佳答案
在这种情况下寻求正确的 react-redux
方法,使用 componentWillReceiveProps
是正确的,在寻求最佳实践时,我建议您阅读以下内容:
redux-saga :它将处理您的异步操作并让一个监听另一个(这是您的用例)
ImmutableJs ,只要它的任何值发生变化,它就会为您处理更改组件属性(在您的情况下是
this.props.filters
,所以它只会为您提供更新的数据,如果它是真的更新了)React.PureComponent ,这可以用来代替
React.Component
,它将通过深入检查 props 对象是否有任何更改来提高处理渲染 React 组件的性能。
同样,如果您没有时间或没有灵 active 在项目中应用此功能,那么在 componentWillReceiveProps
中编写一些检查并没有错。
关于reactjs - 调度后立即使用更新的 redux 状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41263014/