react-native:通过setState

时间:2019-04-20 13:40:35

标签: json reactjs react-native async-await

我有这个简单的代码。

export default class ProductDetail extends Component {

  constructor(props) {
    super(props);
    this.state = { test: null,id:this.props.navigation.state.params.productId };
    console.log(1);
  }

  componentWillMount() {
    console.log(2);
    this.getProductRequest(this.state.id);
    console.log(3);
  }

  async getProductRequest(id) {
    try {
      let api_token = await AsyncStorage.getItem('apiToken')
      let response = await fetch('...')
      let json = await response.json();
      this.setState({test: json});

    } catch(error) {
      //
    }

  }

  render() {
    console.log(4);
    console.log(this.state.test);
    return (
      <View><Text>test</Text></View>
    );
  }
}

现在,我在调试器中对其进行了检查:

我希望得到这样的结果:

  

1

     

2

     

3

     

4

     

{数据:{…},状态:“成功”,...}

但是我明白了:

  

1

     

2

     

3

     

4

     

     

4

     

{数据:{…},状态:“成功”,...}

我认为这意味着render()运行两次!

如何处理此错误?

2 个答案:

答案 0 :(得分:4)

  

我认为这意味着render()运行两次!

它可以:在异步结果可用之前一次,然后在异步结果可用时再次使用setState。这是正常现象,符合预期。

您不能举起第一个渲染来等待异步操作完成。您的选择是:

  1. 在尚无数据时使组件正确呈现。或者,

  2. 如果您不希望在异步操作完成之前完全渲染组件 ,请将该操作移至父组件,仅在数据可用时才渲染该组件,将数据作为道具传递到此组件。

答案 1 :(得分:1)

只需添加到T.J Crowder的答案中,我想做的一件事就是如果尚未收到数据,则返回ActivityIndicator

    ID Value
     1  22
     2  15