reactjs - mapDispatchToProp 不能作为对象工作
问题描述
mapDispatchToProp 在用作对象时不起作用。但是当我通过显式返回调度以经典方式使用它时,它工作得很好。代码如下
const incrementValue = () => ({
type: 'INCREMENT',
});
const decrementValue = () => ({
type: 'DECREMENT',
});
const reducer = (state = initState, action) => {
if(action.type === 'INCREMENT') {
return {
count: state.count + 1,
};
}
if(action.type === 'DECREMENT') {
return {
count: state.count - 1,
};
}
return state;
}
const store = createStore(reducer);
class Counter extends Component {
render() {
const {count, increment, decrement} = this.props;
console.log(count, increment, decrement);
return(
<div className="counter">
<p>{count}</p>
<div className="controls">
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
</div>
)
}
}
const mapStateToProps = (state) => {
return state;
};
const mapDispatchToProp = (dispatch) => {
return {
increment() {
dispatch(incrementValue());
},
decrement() {
dispatch(decrementValue());
}
};
};
const dispatchActions = {
incrementValue,
decrementValue
}; // Not Working // mapDispatchToProps as an object
const CounterContainer = connect(mapStateToProps, mapDispatchToProp)(Counter);
ReactDOM.render(
<Provider store={store}>
<CounterContainer />
</Provider>
, document.getElementById("root"));
当我在第二个参数中使用 dispatchActions 对象而不是 mapDispatchToProp 时,它没有按预期工作。怎么了?编辑:我已经初始化计数如下
const initState = {
count: 0,
};
解决方案
更新:2
您的代码正确您错过的代码中的每一件事都是正确的
您需要在代码中添加以下行initState
let initState = {
count: 0
}
const reducer = (state = initState, action) => {
检查基于您的代码的工作链接https://repl.it/@GopalaKrishnan3/Create-React-App
演示站点 URL https://create-react-app--gopalakrishnan3.repl.co/
更新 3
在这里,您的代码也可以正常工作,您必须在通过 this.props 时正确更改 actionCreater 名称。如下所示,
render() {
const {count, incrementValue, decrementValue} = this.props;
return(
<div className="counter">
<p style={{"fontSize":"55px"}}>{count}</p>
<div className="controls">
<button onClick={incrementValue}>Increment</button>
<button onClick={decrementValue}>Decrement</button>
</div>
</div>
)
}
}
const mapStateToProps = (state) => {
return state;
};
// const mapDispatchToProp = (dispatch) => {
// return {
// increment() { dispatch(incrementValue()); },
// decrement() { dispatch(decrementValue()); }
// };
// };
const dispatchActions = {
incrementValue, // you need change this name while getting props
decrementValue // you need change this name while getting props
};
const CounterContainer = connect(mapStateToProps, dispatchActions)(Counter);
推荐阅读
- python - 字段“id”需要一个数字但得到“std1”,如何获取模型字段的 ForeignKey ID 以在 Django 表单中使用?
- python - Python将一列拆分为多列并将拆分列重新附加到原始数据框中
- scala - 什么时候运行“运行
“出现在 IntelliJ - r - 如何在 R Shiny 中将数字格式更改为印度数字系统?
- python - 迭代器到序列转换的哪个操作快?
- python-3.x - 收到信号时,在python3中旋转(重新打开)文件
- javascript - 如何解决对 JavaScript 的持续复利?
- azure - 获取支持高级磁盘的 Azure VM 大小列表
- python - CVXOPT 似乎为这个简单的二次程序提供了非最佳结果
- sql - 在 SQL 中查找其他表中不存在的列值的所有出现