-1

This my util module, and when I use redux action it does not work.

import {openloading} from '../actions/loading'
export default function (e) {
    openloading(e.font);
}

But in my react component it does work

HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
HouJushang
  • 21
  • 4
  • 1
    You need to dispatch the action, there are different ways to access `dispatch()` from within your component, read http://stackoverflow.com/a/34458710/1744768 – Paul Vincent Beigang Aug 19 '16 at 08:30
  • You cannot simply import and use the action in a component, you need to connect it to redux in your container then the action gets passed as a prop. I prefer `mapDispatchToProps` – ajmajmajma Aug 19 '16 at 15:03

1 Answers1

0

Actions themselves do nothing, which is ironic given the name. Actions merely describe what is going to happen and how state will change. Change actually occurs when these instructions are dispatched to the reducer. As Paul said, you need access to the dispatch method.

Typically, you're calling your util module functions from within your components. In that case, you might want to pass the dispatch method as a parameter.

import { openloading } from '../actions/openloading'

export const myFn = (e, dispatch) => {
  dispatch(openloading(e.font))
}

Your component should get wired up to Redux like so:

import React from 'react'
import { connect } from 'react-redux'
import { myFn } from 'somewhere'

const myComponent = ({ dispatch }) => {

  myFn(e, dispatch)

  return (
    <div>
      { ...whatever }
    </div>
  )
}

const mapStateToProps = (state) => {
  return { ...stuff }
}

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

export default connect(mapStateToProps, mapDispatchToProps)(myComponent)

Note that dispatch is getting passed into the component as a prop in mapDispatchToProps.

Ezra Chang
  • 1,268
  • 9
  • 12