我现在正在研究react-redux。
出现了一些奇怪的情况,这花了我一整天的时间。
这是很多教程中常用的方式。
但它在我的代码中不起作用。
详细来说,没有将事件传递给 Prop 。
const VisibleFilterList = connect(mapStateToProps, mapDispatchToProps)(FilterList);
const mapDispatchToProps = (dispatch) => {
return {
updateFilter : (ev) => dispatch(setFilter(ev.target.value))
}
};
在深入研究这个问题之后,我只是将箭头函数更改为普通函数。然后就可以了!....?!?!
const VisibleFilterList = connect(mapStateToProps, mapDispatchToProps2)(FilterList);
function mapDispatchToProps2(dispatch) {
return {
updateFilter : (ev) => dispatch(setFilter(ev.target.value))
}
}
甚至函数也有相同的返回方法。我想知道为什么箭头功能不起作用。在许多教程中,使用箭头函数看起来更常见。帮助我。
最佳答案
因为 variable
声明不会提升,但是 function
声明会提升。mapDispatchToProps
下面的代码是未定义的,因为没有声明变量 mapDispatchToProps
before connect()
called.except function
lifting up, the import
directive also does lifting declaration up. 变量声明关键字很奇怪,如果你想知道,请看变量声明部分。
更改申报顺序
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
关于javascript - 在 react-redux 中定义函数很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42708321/