在我的渲染功能中,我试图显示一个公司的名称。因此,我调用一个函数getCompanyByShortlink,其中我希望将一个值company_name赋给this.company。我检查了响应,它包含了我需要的所有数据,所以这里没有问题。
然而,这不起作用,该值没有被赋值。如果我输入返回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>
);
}};
发布于 2016-05-16 14:34:22
您不应该在呈现函数中执行异步操作。这样试一试:
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>
);
}
}发布于 2016-05-16 14:24:56
我不确定,但您的返回语句是带有词法this的返回,首先我的意思是编程实践很糟糕。您可以设置类似this.that = that的内容,然后返回that。您还将在返回范围内设置任务,这可能意味着副作用。它可能来自于此。如果有人反对这一点,请大声说出来!
发布于 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方法,所以当您向组件添加更多功能时,它可能会被多次调用。
你就可以走了。
https://stackoverflow.com/questions/37256132
复制相似问题