首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >尝试从存储区映射数组,但获取TypeError:*array*.map不是函数

尝试从存储区映射数组,但获取TypeError:*array*.map不是函数
EN

Stack Overflow用户
提问于 2019-06-26 05:52:07
回答 2查看 29关注 0票数 0

我在一个组件中发出异步请求,并将结果分派到存储。结果是对象数组。而不是在其他组件中,我尝试将其映射到标签中。

问题是我得到了类型错误,因为我的reducer的初始状态是null,并且无法映射null。尝试将其更改为仅为空数组,但得到相同的错误。

我的reducer:

const initialState = {
  currentSearchResult: [],
};

const OrgsListReducer = (state = initialState, action) => action.type === 'GET_ORGS_LIST' ? action.payload : state;

有效载荷本身是正常的

我的组件:

class OrgList extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoaded: false,
            orgList: this.props.currentSearchResult,
        }
    }

    componentDidMount() {
        if (this.props.currentSearchResult !== []) {
            this.setState({
                isLoaded: true
            })
           }
       }

    render() {
        console.log(this.props.currentSearchResult);
        return this.state.isLoaded ?
            <ul>
                {this.state.orgList.map((org) =>
                    <li key={org.id}>{org.login}</li>
                )}
            </ul>
            :
            <h1>Loading...</h1>
    }
}

function mapStateToProps(state) {
    return {
        currentSearchResult: state.currentSearchResult
    }
}


export default connect(mapStateToProps)(OrgList)
EN

回答 2

Stack Overflow用户

发布于 2019-06-26 08:25:56

删除构造函数中的this

this.state = {
    isLoaded: false,
    orgList: props.currentSearchResult,
}

但是为什么要在状态中使用redux值呢?您可以立即使用redux值。

您对currentSearchResult的缺省值有一个空的排列,所以即使没有值,它也可以正常工作。

<ul>
    {this.props.currentSearchResult.map((org) =>
         <li key={org.id}>{org.login}</li>
    )}
</ul>
票数 0
EN

Stack Overflow用户

发布于 2019-06-26 08:32:29

如果action.payload是数组,并且您希望将其放入state.currentSearchResult中,则应该这样做

const OrgsListReducer = (state = initialState, action) => action.type === 'GET_ORGS_LIST' ? {currentSearchResult: action.payload } : state;

state本身就是一个对象,它只包含一个属性currentSearchResult。所以你应该将数组赋值给currentSearchResult。所以状态结构不会被修改。

此外,this.props.currentSearchResult !== []将始终为true。JavaScript中的Array is object。仅当same object compared to itself设置为。因为您想检查数组是否为空,所以执行this.props.currentSearchResult.length > 0

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56762521

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档