14. Recommend模块 + axios获取数据

Recommend模块 + axios获取数据

Recommend模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React, { Component } from 'react'
import { RecommendWrapper, RecommendItem } from '../style'
import { connect } from 'react-redux';

class Recommend extends Component {
render(){
const { list } = this.props

return (
<RecommendWrapper>
{
list.map((item) => {
return <RecommendItem imgUrl={ item.get('imgUrl') }/>
})
}
</RecommendWrapper>
)
}
}

const mapState = (state) => ({
list: state.getIn(['home', 'recommendList'])
})

export default connect(mapState, null)(Recommend);

这里有一个之前没有用到的用法,那就是在style.js中利用styled获取传过来的值(传值到css)
style.js

1
2
3
4
5
export const RecommendItem = styled.div`
width: 280px;
height: 50px;
background :url(${(props) => props.imgUrl})
`

Recomment和之前的List,Topic除去样式和数据上的区别,其余地方基本上没有差异,也就说是同一种模式写出来的(使用connect,从reducer中获取数据)

axios获取数据

在src/pages/home/index.js中,在componentDidMount生命周期函数中发起异步请求,去获取假数据,从而就不必在reducer中写死了。

1
2
3
4
5
6
7
8
9
10
11
12
componentDidMount(){
axios.get('/api/home.json').then((res) => {
const result = res.data.data
const action = {
type: 'change_home_data',
topicList: result.topicList,
articleList: result.articleList,
recommendList: result.recommendList
}
this.props.changeHomeData(action)
})
}

发起dispatch

1
2
3
4
5
6
7
const mapDispatch = (dispatch) => ({
changeHomeData(action){
dispatch(action);
}
})

export default connect(null, mapDispatch)(Home);

/src/pages/home/store/reducer.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import { fromJS } from 'immutable' 

const defaultState = fromJS({
topicList: [],
articleList: [],
recommendList:[]
});

export default (state = defaultState, action ) => {
switch(action.type){
case 'change_home_data':
// state.set 只能改变一个state中的值, fromJS是将一个普通的js对象,转换成为一个 immutable的对象
// state.set('topicList', fromJS(action.topicList))

// state.merge 一次性改变多个值
return state.merge({
topicList: fromJS(action.topicList),
articleList: fromJS(action.articleList),
recommendList: fromJS(action.recommendList),
})
default:
return state;
}
}

代码地址