我有一个父组件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状态中获取道具:
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);
我哪里错了?
我认为你导入Nav是错误的,这里你使用的是一个"默认";导出:
export default connect(mapStateToProps)(Nav);
但是你试着用一个";命名为";导入:
import { Nav } from "./Student/Nav";
CCD_ 5应该作为";默认":
import Nav from "./Student/Nav"