2

The code is:

Test component:

import {add} from './../actions/';

class Test extends Component{

    _add = (){
       this.props.add(1);
    }

    render(){
        <button onClick={this._add}>add</button>  
    }

}

const mapStateToProps = ()=>({
    haha:'haha'
});

export default connect(
    mapStateToProps,
    {add}
)(Test)

Actions:

export const add = value => (dispatch) =>{
    dispatch({
        type:'ADD',
        value:value
    })
}

I click add button there has this error!

What's the issue?

I looked createStore.js and console.log(action). It shows a function.

But Redux's example is not a function. My code is almost the same.

3 Answers 3

2

If you use redux-thunk as a middleware, it will process dispatched function actions....

Another one is redux-promise which will do somethink like the thunk ... but with promises

UPDATE:

This is a model to handle async

export const add = value => (dispatch) => {
   ... do something async
}

LIke this:

export const add = value => (dispatch) => {
   http.get('/path')
       .then(json => 
           dispatch({type: 'RESULT', payload: json}));
}

You action does not have async calls so it could be written like this:

export const add = value => ({
    type:'ADD',
    value:value
})
Sign up to request clarification or add additional context in comments.

6 Comments

I did not use both redux-thunk and redux-promise.
And that's why redux is complaining.. to use async actions ... you need redx-thunk middleware
But I don't know where I have run async actions? I don't use setTimeout and there is no AJAX request
You don't... but the way you write the action... is used to solve async process...look my update
Is the reason closure? I notice it is a closure. Returns an anonymous function
|
2

You are simply missing the arrows => in your arrow function:

export const add = value => (dispatch) => {
    dispatch({
        type:'ADD',
        value:value
    })
}

3 Comments

Sorry, I didn't copy directly, I had made a mistake. Actually, the code is =>
You are still missing an arrow. And for this to work you need redux-thunk middleware.
Thanks ~ Let me try
0

You should write your action creator like this:

export const add = value =>
  ({
    type: 'ADD',
    value: value
  });

The way you connect your action creator to your component (passing it with the shortcut notation { add } as a second parameter to connect) allows you to omit the dispatch since connect will automatically wrap your action creator into a dispatch call when called this way.

1 Comment

Sorry, I didn't copy directly, I had made a mistake. Actually, the code is =>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.