P
P
Pogran2016-08-29 14:29:33
React
Pogran, 2016-08-29 14:29:33

Why does not see the state?

I have such code

const mapDispatchToProps = (dispatch) => {
  return {
    fetchEntities: (limit, offset) => {
      dispatch(fetchEntities(limit, offset)).then(response => {
        this.setState({data: response.data, pageNum: Math.ceil(response.data.length / 2)});
      }) ;
    },
    requestDeleteEntity: (id) => {
      dispatch(requestDeleteEntity(id));
    }
  }
};

and it says to me that this is undefined . How to make a link here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim, 2016-08-29
@Pogran

Let's go in order:
1) it does not see this, because the arrow function does not have its own context ( example , tutorial )
2) it is not necessary to pass this to mapDispatchToProps. If you want to change the state based on new data, then you need to do it in the componentWillReceiveProps method.
3) in order for new props to come, you need to process them in the reducer, and for this you need to call your action crator in mapDispatchToProps. That is, mapDispatchToProps will look like this (note the parentheses after => , this is done so as not to write rerturn {...}):

const mapDispatchToProps = (dispatch) => ({
  fetchEntities: (limit, offset) => dispatch(fetchEntities(limit, offset))
})

for this, of course, import your fetchEntities from actions. In which you have a promise version in which you will process the incoming data. The theory about this is here , or you can see the theory + example in Russian here.
3.5) In mapStateToProps , you must have a corresponding property into which you will pass your new props from the reducer, and because of this, componentWillReceiveProps will work inside which you can call this.setState.

M
Mikhail Osher, 2016-08-29
@miraage

You can't write like that.
mapDispatchToProps calls something like dispatch({type: 'FETCH_ENTITIES_REQUEST', ... }).
Then, when the requests are complete, you need to call dispatch({ type: 'FETCH_ENTITIES_SUCCESS', ... }), which will be processed by the reducer, and your mapStateToProps function will pick up the changes.
Implementation example . (see middleware/api.js)
One more tip.
Due to the fact that mapStateToProps is called on any store changes, it makes sense for performance reasons to use the reselect library so as not to call an idle render on components whose props have not actually changed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question