我有这个功能:
async function search() {
try {
const response = await places.nearbysearch({
location: text, // LatLon delimited by ,
radius: distance, // Radius cannot be used if rankBy set to DISTANCE
type: ['cafe','bakery','meal_delivery','meal_takeaway','restaurant'], // Undefined type will return all types
// rankby: "distance" // See google docs for different possible values
});
const { status, results, next_page_token, html_attributions } = response;
var index = Math.floor(Math.random() * response.results.length);
console.log(response.results[index].name);
restName = response.results[index].name;
console.log(restName);
} catch (error) {
console.log(error);
}
}
它在export default function App() {}
我在视图中制作了这样的文本内容:
return (
<View style={styles.container}>
<View style={{minWidth: '100%', minHeight: '100%', backgroundColor: '#f0fbff', alignFit:'stretch', marginTop: 0, alignItems:'center', justifyContent:'space-evenly'}}>
<Card style={{padding: 5, margin: 1}}>
<Text style={{ fontWeight: 'bold', fontSize: 25, }}>{restName}{"\n"}</Text>
即使restName更新(我按下按钮时运行了search()函数),文本也不会更新,我将如何用此方法实现设置状态或刷新变量。当我console.log restName时,它显示正确的内容,因此我知道变量已更新,只是文本未更新。
简而言之,实际变量会发生变化,但显示的内容不会有所不同
更新我尝试使用setstate,但仍然无法更新这里的功能
var restName = "";
async function search() {
try {
const response = await places.nearbysearch({
location: text, // LatLon delimited by ,
radius: distance, // Radius cannot be used if rankBy set to DISTANCE
type: ['cafe','bakery','meal_delivery','meal_takeaway','restaurant'], // Undefined type will return all types
// rankby: "distance" // See google docs for different possible values
});
const { status, results, next_page_token, html_attributions } = response;
var index = Math.floor(Math.random() * response.results.length);
console.log(response.results[index].name);
this.setState({ restName : response.results[index].name })
console.log(restName);
} catch (error) {
console.log(error);
}
}
答案 0 :(得分:1)
要更新状态,您不能只是重新分配
restName = response.results[index].name
但必须致电setState
this.setState({ restName : response.results[index].name })