我正在尝试学习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);
到目前为止,我的理解:
我注释掉了render函数中需要从状态中提取值的行。然后我派出了行动。操作中的console.log显示商店已更新。据此,我决定商店已正确连接到MyShop.js,而且我的MapDispatchToAction也正在工作。
但是当我尝试从this.state中提取值时,它给了我null。因此mapStateToProps无法正常工作。我的减速机没有发现任何错误。我还在我的reducer中包括了默认情况。所以我猜它应该不会在初始化阶段失败。
最佳答案
connect()
是一个HOC,它通过prop将一个全局状态传递到您的组件中。因此,组件的本地状态没有任何数据。
因此,例如不要尝试调用this.state.beef
代替this.props.beef
。它应该工作正常。
关于javascript - MapStateToProps在react-redux中返回Null,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54148949/