React Redux:为啥这个嵌套组件没有从 redux 状态接收道具?
Posted
技术标签:
【中文标题】React Redux:为啥这个嵌套组件没有从 redux 状态接收道具?【英文标题】:React Redux: Why is this nested component not receiving props from redux state?React Redux:为什么这个嵌套组件没有从 redux 状态接收道具? 【发布时间】:2022-01-16 10:27:54 【问题描述】:我有一个父组件 Course
能够从 redux 获取状态并且我能够成功将其注销:
import React, Component from "react";
import connect from "react-redux";
import SchoolWrapper from "../SchoolWrapper";
export class Course extends Component
constructor(props)
super(props);
console.log("Props in course", props);
render()
return (
<>
<SchoolWrapper>Wrapped component</SchoolWrapper>
</>
);
const mapStateToProps = (state) => (
user: state.user,
);
export default connect(mapStateToProps)(Course);
嵌套在Course
组件中的是另一个组件SchoolWrapper
,它能够从redux 状态获取props:
import React, Component from "react";
import connect from "react-redux";
import Nav from "./Student/Nav";
export class SchoolWrapper extends Component
constructor(props)
super(props);
console.log("SchoolWrapper props", props);
render()
return (
<>
<Nav />
</>
);
const mapStateToProps = (state) => (
user: state.user,
);
export default connect(mapStateToProps)(SchoolWrapper);
但是,Nav
组件或嵌套在此级别的任何其他组件无法从 redux 访问状态。
import React, Component from "react";
import connect from "react-redux";
export class Nav extends Component
constructor(props)
super(props);
console.log("Nav props: ", props);
render()
return (
<div>
nav goes here...
</div>
);
const mapStateToProps = (state) => (
user: state.user,
);
export default connect(mapStateToProps)(Nav);
我哪里错了?
【问题讨论】:
我认为您导入导航错误...export default connect...
,然后您尝试import Nav ...
。应该是import Nav from "./Student/Nav"
。
哦,是的,就是这样。太感谢了。如果有兴趣添加答案,我会接受。
嗯,我会接受的。
【参考方案1】:
我认为您导入 Nav 错误,这里您使用的是“默认”导出:
export default connect(mapStateToProps)(Nav);
但您尝试使用“命名”导入:
import Nav from "./Student/Nav";
Nav
应作为“默认”导入:
import Nav from "./Student/Nav"
【讨论】:
以上是关于React Redux:为啥这个嵌套组件没有从 redux 状态接收道具?的主要内容,如果未能解决你的问题,请参考以下文章
在 React 和 Redux 中使用 Enzyme 进行嵌套组件测试