简体   繁体   English

重新组合withHandlers ...异步?

[英]recompose withHandlers … asynchronously?

Is is possible/safe to use withHandlers with promises? 是否可以/安全地使用带有承诺的处理程序? Ex.: 例:

withHandlers({
    onChange: props => event => {
      props.callAPI(props.data)
        .then(data => props.updateData(data))
    },
...

Thanks! 谢谢!

After some tests I realized that it's working pretty well. 经过一些测试,我意识到它运作良好。 Recompose rocks for building with pure components. 重新构图岩石与纯组分建设。

This is perfectly valid and working pretty well. 这是完全有效的,并且运作良好。

const enhWithHandlers = withHandlers({
  loginUserMutation: props => args => {
    props.updateMutationState(loading: true, error: null });
    props.loginUser(args)
      .then(() =>
        props.updateMutationState({loading: false, error: null }))
      .catch(err =>
        props.updateMutationState({ loading: false, error: err }));
  }
},
...
// then compose like
export default compose(
  reduxConnect,
  gqlConnectLogin,
  gqlConnectRegister,
  enhWithState,
  enhWithHandlers
)(UserLoginRegister);

It helps me to overcome lack of ability to reflect results of graphQl mutation with Apollo client to the wrapped component. 它帮助我克服了将Apollo客户端的graphQl变异结果反映到包装组件的能力不足的问题。 This handles it perfectly and without the need of side effects in the component itself. 这样可以完美地处理它,而不需要组件本身的副作用。

But there are some problems when we use it like this: 但是当我们像这样使用它时会出现一些问题:

compose(
  withState('loginStatus', 'setLoginStatus', {loading: false, error:null}),
  withHandlers({
    loginUserMutation: props => async args => {
      try {
        props.setLoginStatus({loading: true, error: null});
        await props.loginUser(args);
      } catch(error) {
        props.setLoginStatus({...props.loginStatus, error});
      } finally {
        props.setLoginStatus({...props.loginStatus, loading: false});
      }
    }
  })
)

Because the props reference is indeed lost after we await props.loginUser(args) . 因为在我们await props.loginUser(args)之后, props引用确实丢失了。 Then we use it after that is wrong. 然后我们在错误之后使用它。

We should notice not to use it like above. 我们应该注意不要像上面那样使用它。


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM