[英]How to pass data from mapStateToProps to parent component?
This is my component:这是我的组件:
export default const NotesComponent = () => {
return notesList.map((noteProps) => (
<NewsCard {...notesProps} key={notesProps.id} />
))
}
Here is the place where i use this component:这是我使用这个组件的地方:
const Notes = (props: NotesProps) => {
return (
<Container>
<NotesComponent />
</Container>
)
}
const mapStateToProps = (state) => ({
notesData: state.notes.notesData,
})
// and other code so mapStateToProps is working correctly
I don't know how to pass notesData
to NotesComponent
, so the NewsCard
can read the data.我不知道如何将notesData
传递给NotesComponent
,因此NewsCard
可以读取数据。
You can use connect high-order-function from react-redux and export the returned component:您可以使用 react-redux 中的连接高阶函数并导出返回的组件:
import { connect } from 'react-redux'
// Redux state data notesData will be available in props
const NotesComponent = ({notesData}) => {
return notesData.map((noteProps) => (
<NewsCard {...noteProps} key={noteProps.id} />
))
}
const mapStateToProps = (state) => ({
notesData: state.notes.notesData,
})
export default connect(mapStateToProps)(NotesComponent)
Or, as NotesComponent
is a function component, you can use react-hook useSelector instead of using connect
to read redux data:或者,由于NotesComponent
是 function 组件,您可以使用 react-hook useSelector而不是使用connect
来读取 redux 数据:
// in a function component
import { useSelector } from 'react-redux'
...
const notesData = useSelector((state) => state.notes.notesData)
You can also connect parent component ie Notes
with Redux and pass data to NotesComponent
in props (to make NotesComponent
a dumb or reusable component):您还可以将父组件(即Notes
)与 Redux 连接,并在 props 中将数据传递给NotesComponent
(使NotesComponent
成为哑组件或可重用组件):
interface NotesProps {
notesData: write_your_type[]
// ...
}
const Notes = (props: NotesProps) => {
const { notesData } = props
return (
<Container>
<NotesComponent data={notesData} />
</Container>
)
}
const mapStateToProps = (state) => ({
notesData: state.notes.notesData,
})
export default connect(mapStateToProps)(Notes)
// it now exports enhanced (with redux data in props) Notes component
And, NotesComponent
:并且, NotesComponent
:
export default const NotesComponent = ({data}) => {
return data.map((item) => (
<NewsCard {...item} key={item.id} />
))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.