我想使用react-redux中的connect方法将props传递给react hoc高阶函数。
包装函数:
export const withInfiniteScroll = (Component) =>
class WithInfiniteScroll extends React.Component {
componentDidMount() {
window.addEventListener('scroll', this.onScroll, false)
}
componentWillUnmount() {
this.props.initPage()
window.removeEventListener('scroll', this.onScroll, false)
}
onScroll = () => {
(
(window.innerHeight + window.scrollY) >= (document.body.offsetHeight - 500)
&& this.props.stocks.length
)
&& this.props.onPaginatedSearch()
}
render() {
return <Component {...this.props}/>
}
}
组件被包裹:
const StockCard = ({ stocks }) =>
stocks.errmsg === 'ok' ?
stocks.data.map (
(stock, i) =>
<CardContainer key={i}>
<p>{stock.cinvcode}</p>
<p>{stock.cinvname}</p>
</CardContainer>
) : ''
获取临时功能:
const StockCardWithInfiniteScroll = withInfiniteScroll(StockCard)
减速器:
const initState = {
...
stocks: {
errcode: '',
errmsg: '',
data: []
}
}
export const PAGE_INIT = 'PAGE_INIT'
export const initPage = () => ({type: PAGE_INIT, payload: 0})
export const STOCK_FETCH = 'STOCK_FETCH'
export const updateStock = (res) => ({type: STOCK_FETCH, payload: res})
export const onPaginated = (searchStock) => {
return(dispatch) => {
const searchStockNextPage = {
...searchStock,
pageindex: searchStock.pageindex + 1
}
// console.log(searchStockNextPage)
getStock(searchStockNextPage)
.then(res => dispatch(updateStock(res)))
.then(res => console.log(res))
}
}
const stockReducer = (state = initState, action) => {
switch (action.type) {
...
case PAGE_INIT:
return {
...state,
searchStock: {...state.searchStock, page: 0}
}
case STOCK_FETCH:
return {
...state,
stocks: state.stocks.data.concat(action.payload.data)
}
default:
return state
}
}
最后使用connect方法从redux传递道具:
export default connect(
(state) => ({
stocks: state.stock.stocks
}),
{onPaginated, initPage}
)(StockCardWithInfiniteScroll)
我可以在浏览器控制台中看到反馈股票道具,但StockCard无法获得它。