【问题标题】:react-redux how to render response data from apireact-redux 如何从 api 渲染响应数据
【发布时间】:2017-03-06 04:22:33
【问题描述】:

我遵循了 youtube 上的教程之一。当我这样做时,它工作得很好。但是当我尝试不同的 api 时,我得到一个错误 items are not defined。有人可以帮我理解我做错了什么。

谢谢

//动作

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 响应

【问题讨论】:

  • 你尝试一步步调试了吗? 1.检查您的操作payload中的数据。 2. 在reducer 处理完action 后检查你的store 的数据。 3. 检查组件中道具的值。似乎您在主要组件中有一些差异。您正在调用 tweets.response.mainItems 获取推文,但您调用 tweets.statusMessage 获取状态消息。这似乎有点不对劲。也许你应该只打电话给tweets.mainItems?
  • 嗨@VanDanic 我做了调试,一切看起来都很好。它确实打印 statusMessage。 StatusMessage 和 response 处于同一级别, mainItems 是 response 的子项。当我从响应中选择任何子属性时,它会引发错误。 Debug Image Link

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


【解决方案1】:
  1. 在主要组件的 mapStateToProps 函数中,为什么您通过分配 state.tweets.tweets 来访问推文,尽管您没有名为 tweets 的减速器,并且您没有使用 combineReducer 函数(在多个减速器的情况下使用该函数)。李>
  2. 因此您可以通过编写 this.state.tweets 轻松访问推文。您可以在返回之前在 mapStateToProps 中打印状态,这可能有助于调试......

//main component
function mapStateToProp(state){
console.log(state,"=====>")
return {
  tweets : state.tweets
}

【讨论】:

    猜你喜欢
    • 2023-02-21
    • 1970-01-01
    • 2019-08-01
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-04
    • 2022-11-14
    • 2020-04-08
    相关资源
    最近更新 更多