react-redux如何从api呈现响应数据

时间:2017-03-06 04:22:34

标签: reactjs react-redux react-redux-form

我按照youtube上的其中一个教程。当我这样做时,它完全正常。但是当我尝试不同的api时,我收到的错误项目没有定义。有人可以帮我理解我做错了什么。

谢谢

//动作

import axios from 'axios' 
export function fetchTweets(brandUrl, responseCode){
let url = brandUrl + '/api/offer/' + responseCode;
return function(dispatch){
axios.get(url)
  .then((response) => {
    dispatch({
      type: 'FETCH_TWEETS_FULFILLED',
      payload: response.data
    })
  })
  .catch((error) => {
    dispatch({
      type: 'FETCH_TWEETS_REJECTED',
      payload: error
    })
  })
}
}

//减速器

export default function reducer(state = {
tweets: [],
fetching: false,
fetched: false,
error: null
}, action) {
switch(action.type){
case 'FETCH_TWEETS_PENDING' :{
  return { ...state, fetching: true }
}
case 'FETCH_TWEETS_REJECTED' : {
  return { ...state, fetching: false, error: action.payload }
}
case 'FETCH_TWEETS_FULFILLED' : {
  return { ...state, 
    fetching: false, 
    fetched: true, 
    tweets: action.payload }
}
}
return state
}

//主要组件

import React from 'react'
import { connect } from 'react-redux'
import { fetchTweets } from '../actions/tweetsActions'
class Layout extends React.Component{
fetchTweets(){
this.props.dispatch(fetchTweets(brandUrl, responseCode))
}
render(){
const { tweets } = this.props;
if(!tweets.length){
  return <button value="Load" onClick={this.fetchTweets.bind(this)}>Load </button>
}  
console.log(tweets.response.mainItems.length)
return (
  <div>
    <p>{tweets.statusMessage}</p>
    <ul>
    </ul>
  </div>
);
}
}
function mapStateToProp(state){
return {
  tweets : state.tweets.tweets
}
}
export default connect(mapStateToProp)(Layout)

//存储

import { applyMiddleware, createStore } from 'redux'
import thunk from 'redux-thunk'
import promise from 'redux-promise-middleware'
import logger from 'redux-logger'
import reducer from './reducers'
const middleware = applyMiddleware(promise(), thunk, logger())
export default createStore(reducer, middleware)

// API响应 enter image description here

1 个答案:

答案 0 :(得分:0)

  1. 在主要组件的mapStateToProps函数中,为什么你通过分配state.tweets.tweets来访问推文,虽然你没有reducer命名的推文,而你没有使用combineReducer函数(在多个reducer的情况下使用它)。
  2. 因此,您可以通过编写this.state.tweets轻松访问推文。您可以在返回之前在mapStateToProps中打印状态,这可能有助于调试......
  3. //main component
    function mapStateToProp(state){
    console.log(state,"=====>")
    return {
      tweets : state.tweets
    }