当使用mapDispatchToProps函数返回对象以传入连接HOC时,操作创建器在react-redux中不工作。当直接在连接HOC中传递操作创建器时,它在下面的内容中工作。无法理解差异。
不工作:
const mapDispatchToProps = () => {
return {
increment,
decrement
}
}
const WrappedCounter = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(Counter);
工作中:
const WrappedCounter = ReactRedux.connect(mapStateToProps, {
increment,
decrement
})(Counter);
详细代码:
<script type="text/babel" data-plugins="proposal-class-properties" data-presets="env,react">
// Action Creators - You don't need to change these
const increment = () => ({ type: 'increment' });
const decrement = () => ({ type: 'decrement' });
const Counter = (props) => {
return (
<div>
<button className="increment" onClick={props.increment}>Increment</button>
<button className="decrement" onClick={props.decrement}>Decrement</button>
Current Count: <span>{props.count}</span>
</div>
);
};
const mapStateToProps = (state) => {
return { count: state.count }
}
const mapDispatchToProps = () => {
return {
increment,
decrement
}
}
const WrappedCounter = ReactRedux.connect(mapStateToProps, mapDispatchToProps)(Counter);
// Only change code *before* me!
// -----------
const store = Redux.createStore(Redux.combineReducers({
count: (count = 0, action) => {
if (action.type === 'increment') {
return count + 1;
} else if (action.type === 'decrement') {
return count - 1;
} else {
return count;
}
}
}));
ReactDOM.render(
<ReactRedux.Provider store={store}>
<WrappedCounter />
</ReactRedux.Provider>,
document.querySelector('#root')
);
2条答案
按热度按时间9q78igpj1#
写
mapDispatchToProps
有两种有效的语法,这里是这两种语法的组合,但对任何一种都不正确。函数语法
mapDispatchToProps
的“经典”(基本上已经过时)形式是一个函数,它将dispatch
作为参数,并返回组件的属性。这些属性只是普通函数,因此它们需要自己调用dispatch
。它非常冗长,我不建议这样做:
对象语法
定义
mapDispatchToProps
最简单的方法是使用对象速记法,这里返回一个动作创建器函数的字典,react-redux句柄会自动将它们绑定到dispatch
。它看起来像这样:
当使用此语法时,
mapDispatchToProps
不是函数,它只是一个对象。在您的半工作解决方案中,您将
mapDispatchToProps
定义为函数,然后使用connect(mapStateToProps, mapDispatchToProps())(Counter)
调用该函数,您使用了此语法,但多了一个步骤。您定义了一个返回对象的函数。然后调用该函数以获取对象。使用钩子
最现代的编写方法是完全抛弃
connect
高阶组件,使用react-redux钩子。voj3qocg2#
当我调用函数时,Below解决方案正在工作
但我仍然有疑问
对于我在HOC中声明和放置状态,连接它可以正常工作,但mapDispatchToProps在不调用它情况下无法正常工作
mapStateToProps
//刚刚通过悬挂夹具mapDispatchToProps()
//在这里我传递并调用函数