首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从fetch中反应本地集合变量

从fetch中反应本地集合变量
EN

Stack Overflow用户
提问于 2016-05-16 14:18:01
回答 3查看 2.2K关注 0票数 1

在我的渲染功能中,我试图显示一个公司的名称。因此,我调用一个函数getCompanyByShortlink,其中我希望将一个值company_name赋给this.company。我检查了响应,它包含了我需要的所有数据,所以这里没有问题。

然而,这不起作用,该值没有被赋值。如果我输入返回this.company = "test";直接,它的工作非常好。

如果有人能帮助我设置来自我API的正确值,我将非常感激。

谢谢,奥利弗

代码语言:javascript
复制
class Company extends React.Component {
   constructor(props){
   super(props);
   this.shortlink = this.props.shortlink;
   this.company = null;
}

getCompanyByShortlink(shortlink){
  //this works perfectly fine!
  // return this.company = "test";
  fetch('http://192.168.178.96:81/api/v1/companies/'+shortlink).then((response) => response.json())
  .then((responseJson) => {
  //this does not work for any reason.
  return this.company = responseJson.data.company.company_name;
})
  .catch((error) => {
    console.warn(error);
  });
}
render() {
  this.company =   this.getCompanyByShortlink(this.shortlink);
  return (
    <View style={styles.mainContainer}>
    <Text style={styles.mainWelcome}>Your Company: {this.company} </Text>
    </View>
    );
}

};

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-05-16 14:34:22

您不应该在呈现函数中执行异步操作。这样试一试:

代码语言:javascript
复制
class Company extends React.Component {
  constructor(props){
    super(props);
    this.shortlink = this.props.shortlink;

    this.state = {
      company: null
    };

    this.getCompanyByShortlink(this.shortlink).then((company) => {
      this.setState({company});
    });
  }

  getCompanyByShortlink(shortlink){
    //this works perfectly fine!
    // return this.company = "test";

    fetch('http://192.168.178.96:81/api/v1/companies/'+shortlink)
      .then((response) => response.json().data.company.company_name)
      .catch((error) => console.warn(error));
  }

  render() {
    return (
      <View style={styles.mainContainer}>
      <Text style={styles.mainWelcome}>Your Company: {this.state.company} </Text>
      </View>
      );
  }
}
票数 2
EN

Stack Overflow用户

发布于 2016-05-16 14:24:56

我不确定,但您的返回语句是带有词法this的返回,首先我的意思是编程实践很糟糕。您可以设置类似this.that = that的内容,然后返回that。您还将在返回范围内设置任务,这可能意味着副作用。它可能来自于此。如果有人反对这一点,请大声说出来!

票数 0
EN

Stack Overflow用户

发布于 2016-05-16 14:30:12

您需要setState来重新呈现应用程序来显示该值。你可以打电话给

this.setState({ company: responseJson.data.company.company_name})

在您的render()函数集中,Your Company: {this.state.company}

还在componentDidMount()上调用函数componentDidMount(),而不是在render()方法中调用。因为每个状态更新都会调用render方法,所以当您向组件添加更多功能时,它可能会被多次调用。

你就可以走了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37256132

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档