如何将数据从mapStateToProps传递到父组件



这是我的组件:

export default const NotesComponent = () => {
return notesList.map((noteProps) => (
<NewsCard {...notesProps} key={notesProps.id} />
))
}

这是我使用这个组件的地方:

const Notes = (props: NotesProps) => {
return (
<Container>
<NotesComponent />
</Container>
)
}
const mapStateToProps = (state) => ({
notesData: state.notes.notesData,
})
// and other code so mapStateToProps is working correctly

我不知道如何将notesData传递给NotesComponent,所以NewsCard可以读取数据。

您可以使用react redux的connect高阶函数并导出返回的组件:

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)

或者,由于NotesComponent是一个功能组件,您可以使用react hook useSelector而不是使用connect来读取redux数据:

// in a function component
import { useSelector } from 'react-redux'
...
const notesData = useSelector((state) => state.notes.notesData)

编辑:

您还可以连接父组件,即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

并且,NotesComponent:

export default const NotesComponent = ({data}) => { 
return data.map((item) => (
<NewsCard {...item} key={item.id} />
))
}

相关内容

  • 没有找到相关文章

最新更新