React 中结合redux使用axious

1.public/api/api.json

{
   "success":true,
   "data":{
      "topicList":[{
        "id":1,
        "title":"PHP"
    },
    {
        "id":2,
        "title":"C++"
    }],
    "artList":[{
        "id":1,
        "title":"标题1",
        "content":"内容1内容1内容1内容1内容1内容1内容1"
    },
    {
        "id":2,
        "title":"标题2",
        "content":"内容2内容2内容2内容2内容2内容2内容2"
    },
    {
        "id":3,
        "title":"标题3333",
        "content":"内容3内容3内容3内容3内容3内容3内容3"
    }],
    "recommends":[{
        "id":"1",
        "imgUrl":"https://img-bss.csdn.net/202002271210055590.jpg"
    },{
        "id":2,
        "imgUrl":"https://img-bss.csdn.net/1582274713882.jpg"
    },{
        "id":"3",
        "imgUrl":"https://img-bss.csdn.net/202002271210055590.jpg"
    },{
        "id":4,
        "imgUrl":"https://img-bss.csdn.net/1582274713882.jpg"
    }],
    "name":"cj"
   }
}

2.home/index.js

import React, { Component } from 'react'
import { HomeRight, HomeLeft, HomeWrapper } from './styles'
import Topic from './components/Topic'
import List from './components/List'
import Recommend from './components/Recommend'
import Writer from './components/Writer'
import axios from 'axios'
import {connect} from 'react-redux'

class Home extends Component {
    render() {
        return 
{/* */}
} // 当组件挂载完毕 componentDidMount(){ axios.get('/api/api.json').then((res)=>{ const result=res.data.data const action ={ type:'change_home_data', topicList:result.topicList, artList:result.artList, recommends:result.recommends, name:result.name, } // console.log(result) this.props.changeHomeData(action) }) } } const mapDispath=(dispatch)=>({ changeHomeData(action){ dispatch(action) } }); export default connect(null,mapDispath)(Home)

3.home/store/reducer.js

import { fromJS } from 'immutable'
const defaultState = fromJS({
    topicList:[],
    artList:[],
    recommends:[],
    name:''

});

export default (state=defaultState,action)=>{
    switch(action.type){
        case 'change_home_data':
            console.log(action)

             return state.merge({
                topList:fromJS(action.topicList),
                artList:fromJS(action.artList),
                recommends:fromJS(action.recommends)
                // topList:fromJS(action.topicList)
            })
        default:return state;
    }
}

 

你可能感兴趣的:(react)