本机反应:无法解析json参数

时间:2019-04-20 07:13:15

标签: json react-native

我创建了一个获取api的类。

export default class ProductDetail extends React.PureComponent {

  constructor(props) {
      super(props);
      this.state = {
        product : []
    }
  }

  componentDidMount() {
    this.getProductRequest();
  }
  ...

然后创建getProductRequest函数:

async getProductRequest() {
      let response = await fetch('https: ...
      let json = await response.json();
      console.log(json);
      this.setState({ product : json.data});
  }

控制台结果是:

  

{id:225782,标题:“ test”,图像:Array(1),价格:“ 1 $”}

现在在渲染中我得到相同的结果:

render() {

console.log(this.state.product);

return (...

现在我尝试阅读参数:

render() {

console.log(this.state.product.title);

return (...

但是我得到这个错误:

  

TypeError:无法读取属性不足的标题“ ”

怎么了?

编辑:结构:

export default class ProductDetail extends React.PureComponent {

  constructor(props) {
    super(props);
    this.state = {
        product : []
    }
  }

  componentDidMount() {
    this.getProductRequest();
  }

  render() {


    console.log(this.state.product.title);

    return (
      <View>  <Text style={styles.name}>title</Text></View>

    );
  }

  async getProductRequest() {
    try {

        let id = this.props.navigation.state.params.productId;
        let response = await 
              fetch('https://www.example.com/product', {
              method : 'POST',
              headers : {
                  'Accept' : 'application/json',
                  'Content-Type' : 'application/json'
              },
              body : JSON.stringify({
                  id
              })
          });
        let json = await response.json();
        //json: {"data":{id: 225782, title: "test", images: Array(1), price: "1$"},"status":"success"}

        this.setState({ product : json.data});

    } catch(error) {
        //console.log(error)
    }
  }
}

...

4 个答案:

答案 0 :(得分:0)

因为componentDidMount()在第一次执行渲染后重新渲染。因此,当您在返回之前将console.log(this.state.product.title);放在渲染中时,它不会第一次获得标题参数。

重新渲染后,该值将可用。因此,如果您要检查输出,将console.log放在其他位置或将其删除

修改

您可以在componentWillMount()而不是componentDidMount()中调用this.getProductRequest();

 componentWillMount() {
    this.getProductRequest();
  }

答案 1 :(得分:0)

    let product = JSON.parse(this.state.product
     if(product.title){
        console.log(product.title)
     }

使用上面的代码。如果您的状态为字符串,则可能会引起问题。让我知道它是否有效。

答案 2 :(得分:0)

如前所述,反应官方文档:

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree

这确实意味着您的渲染方法第一次无法读取您的产品标题(第一次调用您的渲染方法时,this.state.product仍然是一个空数组)。我建议您检查数组是否为空

render() {

  if (this.state.product) {
    return (
           <Text>Loading...</Text>
  } else
  return (
    <View><Text>{this.state.product.title}</Text></View>
  )
}

请勿使用componentWillMount(),因为这些方法被认为是旧方法,您应该在新代码中避免使用它们。 componentWillMount()

答案 3 :(得分:-1)

如果您的渲染功能确实看起来像您发布的一样,那么这将不起作用。尝试将您的渲染功能调整为类似这样的方式。

render() {
  const { product } = this.state
  if (!product || !product.title) {
    return null
  }
  return (
    <View><Textstyle={styles.name}>product.title</Text></View>
  )
}