这是我的组件:
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
可以读取数据。
答案 0 :(得分:2)
您可以使用 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} />
))
}