首页 > React this.state.names.map is not a function

React this.state.names.map is not a function

1: 遍历数据出错

const Dashboard = React.createClass({
    getInitialState:function(){
        return{
            names:[]
        }
    },
    componentDidMount:function(){    
        var test={
            "list": [
                {
                    "id": 1
                },
                {
                    "id": 7
                },
            ]
        }
        this.setState({names:test})
    },
    render() {
        return (
                <div>
                    {
                        this.state.names.map(function (list) {
                            return <div>Hello, {list.id}!</div>
                        })
                    }
                   
                </div>
            )
    }
})

数据取不到,this.state.names.map is not a function报这个错 是数据类型有问题么,没找出具体问题?


getInitialState 在组建初始化的时候就设定了你想要的 names 的数据,componentDidMount 生命周期方法在组件装载以后执行,在组件的初始化之后。所以此时你的 names 属性在 componentDidMount 中被覆盖为对象 test,但是对象没有数组方法 map()


你的componentDidMount中把names设置为对象了。
对象没有map方法,数组才有


this.state.names.list.map(function (list) {
                            return <div>Hello, {list.id}!</div>
                        })
【热门文章】
【热门文章】