【问题标题】:Why is my react state data undefined in react?为什么我的反应状态数据在反应中未定义?
【发布时间】:2018-10-06 18:51:39
【问题描述】:

我正在使用 API 创建一个 React 360 应用程序来获取数据,然后将其显示在面板上。下面我有以下代码:

export class CryptoControlInformation extends React.Component {


  state = {
    details: {
      description: '',
      links: [],
    }
  };

  componentDidMount() {
    const CRYPTO_CONTROL_PATH = 'https://cryptocontrol.io/api/v1/public/details/coin/bitcoin?key=some_key';
    fetch(CRYPTO_CONTROL_PATH)
      .then(response => response.json())
      .then(data => {this.setState({
        details: {
          description: data["description"],
          links: [...this.state.details.links, ...data["links"] ]
      }})
    })
  }

  render() {
    let links = this.state.details.links;

    ##################################
    console.log(links[0])
    {_id: "5b41d21fa8a741cf4187ec60", type: "reddit", name: "r/Bitcoin Reddit", link: "https://reddit.com/r/Bitcoin/"}
    ####################################


    ####################################
    // Why is this returning undefined? 
    console.log(links[0]["name"]);
    ####################################

    return (
      <View>
        <View style={styles.rightHeader}>
          <Text style={{fontSize: 40}}>Information</Text>
        </View>
        <View>
          <Text>{this.state.details.description}</Text>
        </View>
        <View>
          <Text>{this.state.details.description}</Text>
        </View>
      </View>
    )
  }
}

我无法获取对象内部的信息,我不明白为什么。我知道信息在那里。我可以 console.log 完整地记录对象,但各个部分是未定义的。我究竟做错了什么?我在反应中注意到状态总是必须明确详细。

例如,我发现我不能这样做:

export class Square extends React.Component {
  state = {
   info: undefined
  };

   componentDidMount() {

     // grab information (pseudocode)

     this.setState{info: data}
   }
}

我必须实际绘制出令人讨厌的数据:

export class Square extends React.Component {
  state = {
   info: {
     color: '',
     height: '',
     width: '',
   }
  };

   componentDidMount() {

     // grab information (pseudocode)

     this.setState{info: {
         color: data['red'],
         heigth: data['height'],
         width: data['width']
       }
     }
   }
}

我认为这与我的问题有关。我在正确的轨道上吗?

【问题讨论】:

  • 您不应该在设置新的状态值时访问this.state 值。在使用之前尝试使用之前的状态值将其设置为新状态this.setState( prevState =&gt; {{details: { description: data["description"], links: [...prevState.details.links, ...data["links"] ] }}})@Dan Rubio

标签: reactjs


【解决方案1】:

标准时间问题 - 你没有寻找“反应未定义”,对吧?

当组件加载数据时,render 被调用(最少)两次 - 一次是在初始安装时(无数据),第二次是在数据到达时(setState 强制新渲染)

console.log(在 chrome 中)欺骗你悄悄地更新之前的消息

你可以使用map - 它适用于最初为空的数组 - 或者检查值是否在 jsx 中准备好

{!links.length && <Text>{links[0]["name"]}</Text/>}

...有条件地调用渲染函数,提前返回&lt;Loading /&gt;

不需要使用 setState 和函数(Varun 的评论),它更安全(在某些情况下)但不是强制性的

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-11
    • 2021-03-05
    • 1970-01-01
    • 2020-08-20
    • 2020-10-25
    • 1970-01-01
    • 2017-08-21
    • 2017-12-12
    相关资源
    最近更新 更多