【问题标题】:How to get the api fetch result and view the result inside a card in react native?如何获取 api 获取结果并在反应本机中查看卡片内的结果?
【发布时间】:2017-11-01 06:04:19
【问题描述】:

Profile.js

fetch('http://test.wehubs.in/MobileApp/profile.php',{
    method: 'POST' ,
    headers:{
        'Accept': 'application/json'
    },
    body: JSON.stringify({
        uuid: value
    })
}).then(response =>response.json())
.then((responseData) =>
{
    });

我想通过从 db 中获取内容来显示用户个人资料的详细信息。我还想在卡片中显示这个结果?这怎么可能?

const Profile = (props)=>{
    return(

<Card>
  <CardImage
  source={require('')} style={styles.imagestyle} />
  <CardTitle title="Name" />
  <CardContent text="Location bloodgroup"/>
    <CardButton
      onPress={() => {}}
      title="Back"
      color='red'
    />
</Card>

 );
}

上面是我在卡片中显示详细信息的代码。我想从CardTitle的获取响应中显示用户名。请帮助我。不知道该怎么做。

【问题讨论】:

    标签: reactjs react-native fetch


    【解决方案1】:

    获取代码应该放在 componentDidMount 中。它应该更新组件的状态。

    .then((responseData) => {
      this.setState({ user: responseData });
    });
    

    并且 CardTitle 应该显示状态。

    <CardTitle title={this.state.user && this.state.user.name} />
    

    【讨论】:

    • 我试过这个,但得到错误undefined is not an object evaluating this.state.user
    • 请尝试this.state.user &amp;&amp; this.state.user.name
    • 实际上我没有在 responseData 中获得价值。如何在此处获取编码的 json 数据?
    • 使用 chrome 调试工具。加载页面时,网络请求在网络选项卡中可用。单击网络请求并查看响应。响应包含 JSON 数据。或者,您可以使用 POSTMAN 来测试 API。您需要查看 JSON 数据的形状并将用户或用户名存储在状态中。
    【解决方案2】:

    我已经像这样编辑了获取响应

    }).then(response =>response.json())
    .then((responseData) =>
    {
        this.setState({
            user: (responseData.name),
            usernew: (responseData.bloodgroup),
            loaded:true,
        })
    

    然后我就能够在卡内访问此响应。

    <CardTitle style={styles.containerStyle} title={this.state.user} />
    

    【讨论】:

      猜你喜欢
      • 2021-12-23
      • 2018-01-22
      • 1970-01-01
      • 2021-09-15
      • 2019-09-10
      • 2020-09-21
      相关资源
      最近更新 更多