我正在尝试通过对象数组进行映射来呈现Redux状态,但是我获得map不是一个函数。我可以用console.log我的道具来查看它正在接收,但是看起来好像是在将道具传递到组件之前试图通过它进行映射。如您所见,正如其他人所建议的,我也尝试过使用&&方法,但我得到的只是:
TypeError: myItems.map is not a function
这是我的代码
import React, {Component} from 'react';
import { connect } from 'react-redux';
class RandomComponent extends Component {
state = {
myItems: this.props.myItems
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('Styles: ', this.props.myItems); // Returns object array
}
render() {
const {myItems} = this.props; // also tried this.state
return (
<ul>
{myItems && myItems.map((item) => {
return <span>Hello.</span>
})}
</ul>
);
}
}
const mapStateToProps = state => ({
myItems: state.getmyItems.myItems
});
export default connect(mapStateToProps)(RandomComponent);
根据要求采取的措施和减速器:
import { GET_STYLES } from '../actions/types';
const initialState = {
styleGroups: {},
};
export default function(state = initialState, action){
const { type, payload } = action;
switch(type){
case GET_STYLES:
return {
...state,
styleGroups: payload,
}
default:
return state;
}
}
import axios from 'axios';
import { GET_STYLES } from "./types";
import {getCredential} from "../services/user";
export const getStyles = () => dispatch => {
axios({
"url": "http://***.com/api/styles",
"method": "GET",
"headers": {
"Authorization": getCredential()
}
})
.then(res =>
dispatch({
type: GET_STYLES,
payload: res.data
})
)
.catch(err =>
dispatch({
type: GET_STYLES,
payload: {}
})
);
};
您的initialState是一个对象,将其设置为空数组[]。在catch中,返回一个空数组而不是一个空对象。 &&无效,因为“存在”一个空对象。如果您仍然想使用&&,则将initialState设置为undefined
map
是arrays的函数,您的数据类型可能是object。要迭代和对象,可以使用for ... in