通过react-redux connect调用“ dispatch”后,如何立即使用新道具设置反应状态?

时间:2018-11-20 21:18:21

标签: javascript reactjs redux react-redux

我是React和Redux的新手,我正试图建立一个网站。我正在使用Material-UI组件。 AppSearchBarInput是标题中的输入,用户可以在其中搜索ID(在代码中称为appId)。如果数据库中的appIdfound,那么我想重定向到另一个页面(this.props.history.push('/app/appInfo');)。如果输入为空,则显示带警告消息的小吃栏(AppNotFound),以及数据库中不存在输入时。

onKeyDown方法中,我使用connect调度一个检查ID是否存在于数据库中的操作(dispatch是使用{{1}从getAppInfo调用的) }。然后,我需要立即通过props获取新的Redux状态,以便确定是否找到了id,并据此将redux-thunk local state属性设置为true或false。

问题是调用调度时,我无法在同一方法中获得更新的道具。我可以使用snackBarOpen,但是无法从中更新本地存储。对于这种情况,是否可以使用一些反应生命周期方法或redux技巧解决此问题?

componentDidUpdate

1 个答案:

答案 0 :(得分:0)

从代码的外观看,您没有调度方法。如果确实获取了数据,则您不会获得更新,因为withRouter实际上阻止了shouldComponentUpdate。如果要更新状态,请将connect包裹在withRouter中。

您还应该具有mapDispatchToProps函数。像这样:

const mapDispatchToProps = dispatch => ({
  makeDispatch: () => dispatch({ getAppInfo })
})

所以,而不是:

const AppSearchBarWithStyles = withStyles(AppSearchBarInputStyles)(AppSearchBarInput);
const AppSearchBarWithStylesWithRouter = withRouter(AppSearchBarWithStyles);
export default connect(mapStateToProps, { getAppInfo })(AppSearchBarWithStylesWithRouter);

您应该拥有:

const AppSearchBarWithStyles = withStyles(AppSearchBarInputStyles)(AppSearchBarInput);
AppSearchBarWithStylesWithConnect = connect(mapStateToProps, mapDispatchToProps)(AppSearchBarWithStyles);
export default withRouter(AppSearchBarWithStylesWithConnect);

请查看以下内容:https://reacttraining.com/react-router/core/api/withRouter