【发布时间】:2019-06-06 12:27:28
【问题描述】:
我正在尝试学习 redux。我已经成功实现了 mapDispatchedToProps。但是 mapStateToProps 函数返回 Null。我的代码如下。
MeatShopReducer
const initial_state = {
beefs: 20,
muttons: 30,
chickens: 40
};
const MeatShopReducer = (state = initial_state, action) => {
switch (action.type) {
case "ADD_BEEF":
console.log("action dispatched");
var new_state = { ...state };
new_state.beefs = new_state.beefs - 1;
console.log(new_state);
//return new_state;
return new_state;
default:
console.log("default:");
console.log(state);
return state;
}
};
export default MeatShopReducer;
MeatShop.js
import React, { Component } from "react";
import { connect } from "react-redux";
class MeatShop extends Component {
render() {
console.log("render fired");
console.log(this.state);
return (
<div>
<div>Meat Shop Redux</div>
<table>
<thead>
<tr>
<th>Item</th>
<th>Unit</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>Beef</td>
<td>{this.state.beef}</td>
<td>{this.state.beef}</td>
<td>
<button onClick={this.props.ADD_BEEF}>Add</button>
</td>
</tr>
<tr>
<td>Mutton</td>
<td>{this.state.mutton}</td>
<td>{this.state.mutton}</td>
<td>
<button>Add</button>
</td>
</tr>
<tr>
<td>Chicken</td>
<td>{this.state.chicken}</td>
<td>{this.state.chicken}</td>
<td>
<button>Add</button>
</td>
</tr>
</tbody>
</table>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
ADD_BEEF: () => dispatch({ type: "ADD_BEEF" })
};
};
const mapStateToProps = state => {
return {
beef: state.beefs,
mutton: state.muttons,
chicken: state.chickens
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(MeatShop);
到目前为止我的理解: 我注释掉了渲染函数中需要从状态中提取值的行。然后我派出行动。操作中的 console.log 显示商店已更新。由此我决定商店已正确连接到 MyShop.js,而且我的 MapDispatchToAction 也在工作。
但是当我尝试从 this.state 中提取值时,它给了我 null。所以 mapStateToProps 不起作用。我在减速器中没有发现任何错误。我还在我的减速器中包含了一个默认情况。所以我猜它不应该在初始化阶段失败。
【问题讨论】:
-
(旁注)您可以使用
var new_state = { ...state, beefs: state.beefs-1 };来避免突变。 -
@jcal ..谢谢你的建议..你能给我一些关于更新商店同时避免突变的好学习材料吗?由于我是新手,我发现很难理解 redux。
-
这整个没有突变的东西来自函数式编程范式(fp)。在 javascript 中搜索有关 fp 的文章。这可以提高您对此的理解。
标签: javascript redux react-redux