请问,redux 怎么取远程数据?

阅读 6.4k
3 个回答

ls说的, 可以用react DidMount 得到,
也可以用redux 来
官方文档有方法: fetch
用中间件, 大概是这样~~~

import {ajax} from '../middleware/ajax'
const createStoreWithMiddleware = applyMiddleware(
   ajax
)(createStore)

import 'isomorphic-fetch'
export const ajax = store => next => action =>{
        fetch('url').then(res => res.json())
        .then(data =>{
            console.log(data.id)
        return next(action)
    })
    }
}

还可以官方有个例子 async

function fetchPosts(reddit) {
  return dispatch => {
    dispatch(requestPosts(reddit))
    return fetch(`https://www.reddit.com/r/${reddit}.json`)
      .then(response => response.json())
      .then(json => dispatch(receivePosts(reddit, json)))
  }
}

不用Redux:
在react componentDidMount周期中获取数据;

getInitialState() {
    return {
      data: []
    };
},
componentDidMount() {
   //这里获取数据并渲染到state里面;
   setState({
   });
}

用Redux,那就在action里面写获取数据

export default function getData() {
    
    ... //在这里通过ajax获取数据data并简单处理
    
    return {type: ADD_DATA, data}
}

然后再reducer里面处理action

export default function myReducer(state=initialstate, action) {
    switch(action.type) {
        case: 'ADD_DATA',
        return [
            //这里要按照state结构整合action的数据。比如state里面是text和name,如果action返回是数组还要进行遍历操作。
            {
                name: action.name,
                text: action.text
            }
            ...state
        ]
    }
}

如何不实用fetch 换成 ajax

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题