【发布时间】: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)
【问题讨论】:
-
你尝试一步步调试了吗? 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