mapDispatchToProps to be explicit

reactjs redux

72 观看

1回复

474 作者的声誉

In react/redux I'm trying to convert this mapDispatchToProps to be explicit:

const mapDispatchToProps = { createOrganization }

I tried this:

const mapDispatchToProps = (dispatch) => {
  return {
    createOrganization: (organization) => {
      dispatch(createOrganization(organization))
    }
  }
}

And this is the action

export const createOrganization = (organization) => ({
  type: ACTION_CREATE_ORGANIZATION,
  payload: api.createOrganization(organization),
})

But It's nor working. What can I do? Am I missing something?

The error is "Cannot read property 'then' of undefined". What it's happening is that once I enter a code, it should create an organization and redirect me to the page /dashboard, but it's not working

  handleClick = (e, formData) => {
    e.preventDefault()
    if (formData.betaCode && formData.organization && this.props.userData) {
      this.props.createOrganization({
        name: formData.organization,
        owner: {
          id: this.props.userData.id,
          name: this.props.userData.login,
          ownerAvatar: this.props.userData.avatar_url
        },
        beta_code: formData.betaCode

      })
      .then(() => {
        this.props.history.push('/dashboard')
      })
    }
  }
作者: Liz Parody 的来源 发布者: 2017 年 12 月 27 日

回应 1


1

5096 作者的声誉

Based on your code, createOrganization action should be an async. Something similar to:

const = createOrganization = organization => dispatch =>
  api.createOrganization(organization)
    .then(
      response => dispatch({ type: ACTION_CREATE_ORGANIZATION, payload: response}),
      error => dispatch({ type: ACTION_CREATE_ORGANIZATION_ERROR, payload: error}),
    )

But it's not enough, you should install redux-thunk && redux-promise to handle such kind of action.

Rest of your code shouldn't be changed. Then you will be able to use mapDispatchToProps as you want:

const mapDispatchToProps = { createOrganization }

Hope it make sense. Async flow in redux

作者: The Reason 发布者: 2017 年 12 月 27 日
32x32