【问题标题】:React Native set var from fetch来自 fetch 的 React Native set var
【发布时间】:2016-05-16 14:18:01
【问题描述】:

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

但是这不起作用,没有分配值。如果我输入 return this.company = "test";直接,它工作得很好。

如果有人可以帮助我设置来自我的 API 的正确值,我将不胜感激。

谢谢, 奥利弗

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>
    );
}

};

【问题讨论】:

  • this.company = this.getCompanyByShortlink(this.shortlink); 将 this.company 设置为 promise 而不是 promise 的解析值。

标签: javascript reactjs react-native react-android


【解决方案1】:

您不应该在渲染函数中执行异步操作。试试这个方法:

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>
      );
  }
}

【讨论】:

  • 是的,强制重新渲染的正确方法是设置状态。除此之外,OP 的代码混合同步和异步的解释会有所帮助。也就是说,OP 的 getCompanyByShortlink 不返回值,它返回一个承诺,并且 OP 的代码假定它返回一个值。
  • 非常感谢!我解决了!这也很有帮助:facebook.github.io/react-native/docs/…Cheers
【解决方案2】:

我不确定,但是您的 return 语句是带有词法 this 的 return,首先我的意思是编程习惯不好。您可以设置类似this.that = that 的内容,然后返回that。您还在 return 中设置了一个赋值,这可能意味着副作用。它可能来自于此。如果有人反对这一点,请说出来!

【讨论】:

    【解决方案3】:

    您需要 setState 重新渲染应用程序以显示该值。你可以打电话

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

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

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

    你会很高兴的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-05
      • 2018-09-16
      • 2016-07-17
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      • 2018-11-24
      • 2018-03-12
      相关资源
      最近更新 更多