11.拆分state把请求api文章列表,数据渲染到页面上

  1. const initState = {
  2. num: 160,
  3. list: []
  4. }
  5. // reducer
  6. export const weight = (state = initState , action) => {
  7. switch (action.type) {
  8. case EAT:
  9. return {...state, num: state.num + 10}
  10. case HUNGRY:
  11. return {...state, num: state.num - 10}
  12. case ARTICLE_LIST:
  13. console.log('action',action)
  14. return {...state, list: action.playload.article}
  15. default:
  16. return initState
  17. }
  18. }
  1. export const getArticle = () =>{
  2. return dispatch =>{
  3. setTimeout(()=>{
  4. // dispatch(eat('煎饼'))
  5. axios.get('/v1/article/list').then(res=>{
  6. console.log('article',res)
  7. //做了一个分发
  8. dispatch({type:ARTICLE_LIST,playload:res.data})
  9. })
  10. },2000)
  11. }
  12. }

页面渲染

  1. const {num, eat, hungry , eatAsync, getArticle, list} = this.props
  2. render
  3. {list.map((item,index)=>{
  4. return <div key={index}>
  5. {item.title}
  6. </div>
  7. })}
  8. export default connect((state)=>{
  9. return {num: state.num,list:state.list}
  10. },{eat,hungry,eatAsync,getArticle})(App)