鍍金池/ 問答/網(wǎng)絡(luò)安全  HTML/ react state

react state

想要在render中使用this.state.data 一直報錯

import React from 'react'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import { getListData } from '../../../fetch/home/home'

import ListCompoent from '../../../components/List'
import LoadMore from '../../../components/LoadMore'

import './style.less'

class List extends React.Component {
    constructor(props, context) {
        super(props, context);
        this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this);
        this.state = {
            data: [],
            hasMore: false,
            isLoadingMore: false,
            page: 0
        }
    }
    render() {
        console.log(this.state)
        return (
            <div>
                <h2 className="home-list-title">猜你喜歡</h2>
               {this.state.data}  
               {/*  只要添加上面的語句就會報錯 */}
            </div>
        )
    }
    componentDidMount() {
        // 獲取首頁數(shù)據(jù)
        this.loadFirstPageData()
    }
    // 獲取首頁數(shù)據(jù)
    loadFirstPageData() {
        const cityName = this.props.cityName
        const result = getListData(cityName, 0)
           // 處理數(shù)據(jù)
        result.then(res => {
            return res.json()
        }).then(json => {
            const hasMore = json.hasMore
            const data = json.data

            this.setState({
                hasMore: hasMore,
                // 注意,這里講最新獲取的數(shù)據(jù),拼接到原數(shù)據(jù)之后,使用 concat 函數(shù)
                data: this.state.data.concat(data)
            })
        }).catch(ex => {
            if (__DEV__) {
                console.error('首頁”猜你喜歡“獲取數(shù)據(jù)報錯, ', ex.message)
            }
        })
    }
  
 
 
}

export default List

debug 看到state中是包含這個屬性的,但是爲(wèi)什麼不能使用呢?還請指教下。

回答
編輯回答
涼薄

this.state.data得是一個元素吧?

2018年7月7日 21:36
編輯回答
柚稚

把變量用組件包裹一下,比如:

render() {
    return() {
         <div>
             <h2 className="home-list-title">猜你喜歡</h2>
             <div>{this.state.data}</div>
             <div>{this.state.page}</div>
         </div>
    }
}
2017年4月1日 16:06