gpt4 book ai didi

javascript - MapStateToProps 在react-redux中返回Null

转载 作者:行者123 更新时间:2023-11-28 17:12:09 24 4
gpt4 key购买 nike

我正在尝试学习 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);

到目前为止我的理解:我注释掉了渲染函数中需要从状态中提取值的行。然后我 dispatch 了行动。操作中的 console.log 显示商店已更新。由此我得出结论,商店已正确连接到 MyShop.js,而且我的 MapDispatchToAction 也正常工作。

但是当我尝试从 this.state 中提取值时,它给了我 null。所以 mapStateToProps 不起作用。我没有发现我的 reducer 有任何错误。我还在我的 reducer 中包含了一个默认情况。所以我猜它应该不会在初始化阶段失败。

最佳答案

connect() 是一个 HOC,它通过 props 将一段全局状态传递到您的组件中。因此组件的本地状态没有任何数据。

因此,不要调用 this.state.beef,而是尝试 this.props.beef。应该可以正常工作。

关于javascript - MapStateToProps 在react-redux中返回Null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54148949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com