鍍金池/ 問答/HTML/ react里return的問題

react里return的問題

首先一個(gè)方法,return一個(gè)對(duì)象:

selectStatus(num) {
    if (num === '1') {
       return  {
        text:'直播預(yù)告中',
        num:123
      };

    }
  }

一個(gè)接口請(qǐng)求:

.then(res => {
        const { body } = res;
       
        this.setState({
        
          num: body.content.data[0].onlineNum  //string格式,值為'1'
        })
      })
      .catch()

在render方法里渲染時(shí)調(diào)用:

<div>{this.selectStatus(this.state.num).text}</div>   //為什么這樣拿不到text?感覺是兩個(gè)this的問題。

報(bào)錯(cuò)提示:

text is undefind
回答
編輯回答
司令

你不能把 this.selectStatus('1').text作為一個(gè)react child,最好的方法是

render() {
    const { text } = this.selectStatus('1');
    return (
        <div>{text}</div>
    ); 
}
2017年5月28日 03:04
編輯回答
撥弦

你先去看看react child是什么就懂了

2017年7月4日 13:33
編輯回答
怣痛

我直接這樣是可以跑通的

export default class extends React.Component {
    selectStatus(num) {
        if (num === '1') {
            return  {
                text:'直播預(yù)告中',
                num:123
            };

        }
    }
    render() {
        return <div>{this.selectStatus('1').text}</div>
    }
}

除非你寫的是這樣才會(huì)報(bào)你那個(gè)錯(cuò)吧:

return <div>{this.selectStatus('1')}</div>
2018年8月10日 08:09
編輯回答
舊顏

目前寫法沒問題
傳入1沒問題
傳入不是1肯定報(bào)錯(cuò)都沒有返回東西
你這個(gè)錯(cuò)是直接渲染對(duì)象啊 <div>{this.selectStatus('1')}</div>
你確定你項(xiàng)目寫的就是 你問的這代碼嗎?

2017年5月31日 20:32