【发布时间】:2016-08-21 15:56:47
【问题描述】:
我有一个组件 TreeNav,其数据来自 api 调用。我已经设置了 reducer/action/promise 和所有的管道,但是当我在数据上调用 map() 时,在组件渲染中,得到“Uncaught TypeError: Cannot read property 'map' of undefined”。
故障排除显示 TreeNav render() 被调用了两次。第二次是在数据从 api 返回之后。但由于第一次渲染()错误,第二次渲染()永远不会运行。
这是我的代码文件:
-------- reducers/index.js ---------
import { combineReducers } from 'redux';
import TreeDataReducer from './reducer_treedata';
const rootReducer = combineReducers({
treedata: TreeDataReducer
});
export default rootReducer;
-------- reducers/reducer_treedata.js ---------
import {FETCH_TREE_DATA} from '../actions/index';
export default function (state=[], action) {
switch (action.type) {
case FETCH_TREE_DATA: {
return [action.payload.data, ...state];
}
}
return state;
}
-------- 动作/index.js --------
import axios from 'axios';
const ROOT_URL = 'http://localhost:8080/api';
export const FETCH_TREE_DATA = 'FETCH_TREE_DATA';
export function fetchTreeData () {
const url = `${ROOT_URL}/treedata`;
const request = axios.get(url);
return {
type: FETCH_TREE_DATA,
payload: request
};
}
-------- 组件/tree_nav.js --------
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchTreeData} from '../actions/index';
class TreeNav extends Component {
constructor (props) {
super(props);
this.state = {treedata: null};
this.getTreeData();
}
getTreeData () {
this.props.fetchTreeData();
}
renderTreeData (treeNodeData) {
const text = treeNodeData.text;
return (
<div>
{text}
</div>
);
}
render () {
return (
<div className="tree-nav">
{this.props.treedata.children.map(this.renderTreeData)}
</div>
);
}
}
function mapStateToProps ({treedata}) {
return {treedata};
}
// anything returned from this function will end up as props
// on the tree nav
function mapDispatchToProps (dispatch) {
// whenever selectBook is called the result should be passed to all our reducers
return bindActionCreators({fetchTreeData}, dispatch);
}
// Promote tree_nav from a component to a container. Needs to know about
// this new dispatch method, fetchTreeData. Make it available as a prop.
export default connect(mapStateToProps, mapDispatchToProps)(TreeNav);
【问题讨论】:
-
该操作不应该在
axios.get().then()回调中吗?并且有效负载是响应而不是请求。 -
忘记我之前的问题,我想你正在使用promise中间件。你是吗?
-
是的,使用 promise 中间件,而且我对 react/redux 还很陌生,我可能不知道何时/如何以其他方式进行操作。使用从 Udemy 课程中获得的代码。
标签: javascript reactjs redux react-redux