[英]Chaining redux connect mapStateToProps , to access props inside mapDispatchToProps
[英]mapStateToProps and mapDispatchToProps is not sending props to component
请我正在处理 redux 项目,但返回到 mapStateToProps 的数据未发送到组件。 Console.log 道具未定义
LiveEvent.protoTypes = {
event: PropTypes.object.isRequired,
error: PropTypes.string,
};
const mapDispatchToProps = (dispatch) => {
return {
getSingle: (values) => {
console.log(Creators, "creators")
dispatch(Creators.getOneEvent(values));
},
};
};
const mapStateToProps = (state) => (
console.log(state.event.event, "state from liveEvent"),
{
event: state.event.event,
error: state.event.error_message,
}
);
export default connect(mapStateToProps, mapDispatchToProps)(LiveEvent);
function LiveEvent({match}, props) {
console.log(props, "props")
有什么做错了吗
function LiveEvent({match}, props) {
道具 object 出现在 function 的第一个参数中。 没有任何东西作为第二个参数传递。 因此,您正在解构 props 以获取match
,然后创建一个名为props
的无用变量,但与实际 props 无关。
如果您想在不解构的情况下获得整个道具 object ,请将您的代码更改为:
function LiveEvent(props) {
// Do whatever with props, including things like
// const { match } = props
}
或者,使用解构将您关心的道具分配给局部变量:
function LiveEvent({ match, event, error, getSingle }) {
}
啊,你有逗号,我把它读成控制台后面的分号。 它工作正常。
隐式返回
<LiveEvent event={...} error={...} />
要使用控制台进行调试,您必须使用大括号 use return 语句:
const mapStateToProps = (state) => { console.log(state.event.event, "state from liveEvent"), return { event: state.event.event, error: state.event.error_message, } };
2. 在你的组件中定义 proptypes 表示组件应该传递 props。
组件道具
LiveEvent.protoTypes = { event: PropTypes.object.isRequired, error: PropTypes.string, };
此代码期望在组件本身中有道具:
<LiveEvent event={...} error={...} />
与 redux 连接的组件不会从中获取道具,因为它的首要任务是检查并从组件本身获取道具。
因此,从您的组件中删除 proptypes,以便组件可以接收 redux 道具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.