Reputation: 15
I'm on studying react-redux now.
There was something weird situation, and it took my whole day hours.
this is a common way in many tutorials.
But it didn't work in my code.
In detail, didn't pass the event to props.
const VisibleFilterList = connect(mapStateToProps, mapDispatchToProps)(FilterList);
const mapDispatchToProps = (dispatch) => {
return {
updateFilter : (ev) => dispatch(setFilter(ev.target.value))
}
};
After a lot of digging this problem, I just changed the arrow function to a normal function. Then it works!....?!?!
const VisibleFilterList = connect(mapStateToProps, mapDispatchToProps2)(FilterList);
function mapDispatchToProps2(dispatch) {
return {
updateFilter : (ev) => dispatch(setFilter(ev.target.value))
}
}
Even the functions are having same return method. And I wonder why the arrow function doesn't work. In many tutorials, using arrow function looks more common. Help me.
Upvotes: 1
Views: 66
Reputation: 30676
because variable
declaration will not lifting up,but function
declaration does.the code below mapDispatchToProps
is undefined,because not declared an variable mapDispatchToProps
before connect()
called.except function
lifting up,the import
directive also does lifting declaration up.the variable declaration keywords is strange,if you want to know see Variable Declaration section.
const mapDispatchToProps = (dispatch) => {
return {
updateFilter : (ev) => dispatch(setFilter(ev.target.value))
}
};
const VisibleFilterList = connect(mapStateToProps, mapDispatchToProps)(FilterList);
describe('decalration lifting up', () => {
test('constants not lifting up', () => {
const foo = bar;
const bar = () => {};
var fuzz = buzz;
const buzz = 'buzz';
expect(foo).toBeUndefined();
expect(fuzz).toBeUndefined();//not 'buzz'
});
test('variable not lifting up', () => {
let foo = bar;
let bar = () => {};
expect(foo).toBeUndefined();
});
test('function lifting up', () => {
let foo = bar;
function bar() {};
expect(foo).toEqual(expect.any(Function));
});
});
//I think these variable declarations,first allocate fuzz & buzz memory
//,then execute assignment.so const fuzz=buzz can works
//,because buzz be found in memory
const fuzz = buzz;//undefined
const buzz = 'buzz';
//in this case,buzz has not allocate memory,so it can't be found by assignment.
const fuzz = buzz;//throws an exception: fuzz is not defined
Upvotes: 2
Reputation: 2402
Change the arrow function to
mapDispatchToProps = (dispatch) => {
return {
updateFilter : (ev) => dispatch(setFilter(ev.target.value))
}
};
This answer is based on the visible code that you shared, if you show more code I may have to update this answer.
Regardless, get used to using the arrow functions because it is the future.
Upvotes: 0